<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 商品操作类
 * @package  htdocs
 * @subpackage  module
 * @author   allen.qiang
 * @version 1.0
 */  

define('COLOR_SPECGROUPID' , 1) ;          //颜色规格组号

define('BRAND_TAGGROUPID' , 6) ;           //品牌标签组号

define('UNIT_TAGGROUPID' , 7) ;    		   //单位标签组号

define('SIZE_TAGGROUPID' , 2) ;    		   //尺码标签组号

define('BIGCATEGORY_TAGGROUPID' , 3) ;     //大分类标签组号

define('MIDCATEGORY_TAGGROUPID' , 4) ;     //中分类标签组号

define('SMALLCATEGORY_TAGGROUPID' , 5) ;   //小分类标签组号

define('JPG',2);
define('PNG',3);
define('GIF',1);

class goodsHandler {

    private $dbca;
	
	public function __construct( $dbca=null ) {
		if (!is_null($dbca))
			$this->dbca = $dbca;
	}

    /**
     * 查询三级商品信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
            'postID' => int 三级网购号
            'twoPostID' => int 二级网购号
            'product_code' => string 商品SKU
            'goodsName' => string 商品名称
            'forsale' => int 是否可销售
            'useFlg' => int 是否已下架
            'sortname' => string 排序字段
            'sortorder' => string 排序方式
            'page' => int 分页页码
            'rp' => int 分页页数
     * )
     * @return null|array
     */
    public function searchGoodsSale( &$arg_array ) {
        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //二级网购号
        if (isset($arg_array['twoPostID']) && is_numeric($arg_array['twoPostID'])) {
            $sql .= ' AND twoPostID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['twoPostID'];
        }

        //三级网购号
        if (isset($arg_array['postID']) && is_numeric($arg_array['postID'])) {
            $sql .= ' AND postID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['postID'];
        }

        //商品SKU
        if (isset($arg_array['product_code']) && !empty($arg_array['product_code'])) {
            $sql .= ' AND product_code = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['product_code'];
        }

        //商品名称
        if (isset($arg_array['goodsName']) && !empty($arg_array['goodsName'])) {
            $sql .= ' AND goodsName LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . $arg_array['goodsName'] . '%';
        }
        
        //商品编号
        if (isset($arg_array['mainPostID']) && !empty($arg_array['mainPostID'])) {
            $sql .= ' AND mainPostID = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['mainPostID'];
        }

        //上下架
        if (isset($arg_array['forsale']) && in_array($arg_array['forsale'], array(0, 1))) {
            $sql .= ' AND forsale = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['forsale'];
        }

        //有无库存
        if (isset($arg_array['useFlg']) && in_array($arg_array['useFlg'], array(0, 1))) {
            $sql .= ' AND useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }

        //大分类号
        if (isset($arg_array['bigCategoryID']) && is_numeric($arg_array['bigCategoryID'])) {
            $sql .= ' AND bigCategoryID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['bigCategoryID'];
        }

        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计分类数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM goods_sale ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM goods_sale ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            $goodsHandler = new goodsHandler();

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'goodsID' => $item->goodsID,
                    'goodsName' => $item->goodsName,
                    'postID' => $item->postID,
                    'bigCategoryID' => $item->bigCategoryID,
                    'bigCategoryName' => $item->bigCategoryName,
                    'midCategoryID' => $item->midCategoryID,
                    'midCategoryName' => $item->midCategoryName,
                    'smallCategoryID' => $item->smallCategoryID,
                    'smallCategoryName' => $item->smallCategoryName,
                    'forsale' => $item->forsale,
                    'spec' => $item->spec,
                    'useFlg' => $item->useFlg,
                    'marketPrice' => $item->marketPrice,
                    'salePrice' => $item->salePrice,
                    'pointPrice' => $item->pointPrice,
                    'addPoints' => $item->addPoints,
                    'salePoints' => $item->salePoints,
                    'discountFlg' => $item->discountFlg,
                    'pointsByFlg' => $item->pointsByFlg,
                    'brandID' => $item->brandID,
                    'brandName' => $item->brandName,
                    'unitID' => $item->unitID,
                    'unitName' => $item->unitName,
                    'brief' => $item->brief,
                    'description' => $item->description,
                    'goodsMainPic' => $this->setImgLink($item->goodsMainPic),
                    'img_link' => $this->setImgLink($item->goodsMainPic),
                    'memo' => $item->memo,
                    'templates' => $item->templates,
                    'goodsLength' => $item->goodsLength,
                    'goodsWidth' => $item->goodsWidth,
                    'goodsHeight' => $item->goodsHeight,
                    'goodsWeight' => $item->goodsWeight,
                    'barcode' => $item->barcode,
                    'product_code' => $item->product_code,
                    'twoPostID' => $item->twoPostID,
                    'product_mainID' => $item->product_mainID,
                    'mainPostID' => $item->mainPostID,
                    'site_id' => $item->site_id,
                    'link' => $this->setLink( $item->postID ),
                    'wap_link' => $this->setWapLink( $item->postID ),
                    'bigCategoryLink' => $this->setCategoryLink($item->bigCategoryID),
                    'midCategoryLink' => $this->setCategoryLink($item->bigCategoryID, $item->midCategoryID),
                    'smallCategoryLink' => $this->setCategoryLink($item->bigCategoryID, $item->midCategoryID, $item->smallCategoryID),
                    'enableSaleAmount' => $item->enableSaleAmount,
                    'shelfLife' => $item->shelfLife,
                    'syncID' => $item->syncID,
                    'syncopate' => $item->syncopate,
                    'birthID' => $item->birthID,
                    'birthcard' => $item->birthcard,
                );
            }

            if ((isset($arg_array['postID']) && !empty($arg_array['postID'])) || (isset($arg_array['product_code']) && !empty($arg_array['product_code']))) {
                return $item_array[0];
            } else {
                return $item_array;
            }

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }
    
    /**
     * 根据关键字查询二级商品
     * @param array $arg_array                      查询参数数组
     * $arg_array = array (
            'forsale' => int 是否可销售
            'useFlg' => int 是否已下架
            'sortname' => string 排序字段
            'sortorder' => string 排序方式
            'page' => int 分页页码
            'rp' => int 分页页数
     * )
     * @return null|array
     */
    public function searchKeyWordGoods( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //上下架
        if (isset($arg_array['forsale']) && in_array($arg_array['forsale'], array(0, 1))) {
            $sql .= ' AND gl.forsale = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['forsale'];
        }

        //有无库存
        if (isset($arg_array['useFlg']) && in_array($arg_array['useFlg'], array(0, 1))) {
            $sql .= ' AND gl.useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }
		
        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }
		
        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计分类数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM goods_list gl JOIN goods_keyword gk ON gl.postID = gk.postID ' . $sql . ' GROUP BY gk.postID';
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                if (!$count_array) {
                    $arg_array['count'] = 0;
                    return null;
                }
                $item_count = $count_array[0]->item_count;
                if ($count_array[0]->item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' GROUP BY gk.postID ORDER BY gl.%s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' GROUP BY gk.postID ORDER BY gl.%s gl.%s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT gl.* FROM goods_list gl JOIN goods_keyword gk ON gl.postID = gk.postID ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;
			
            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'goodsID' => $item->goodsID,
                    'goodsName' => $item->goodsName,
                    'postID' => $item->postID,
                    'bigCategoryID' => $item->bigCategoryID,
                    'bigCategoryName' => $item->bigCategoryName,
                    'midCategoryID' => $item->midCategoryID,
                    'midCategoryName' => $item->midCategoryName,
                    'smallCategoryID' => $item->smallCategoryID,
                    'smallCategoryName' => $item->smallCategoryName,
                    'forsale' => $item->forsale,
                    'spec' => $item->spec,
                    'useFlg' => $item->useFlg,
                    'marketPrice' => $item->marketPrice,
                    'salePrice' => $item->salePrice,
                    'pointPrice' => $item->pointPrice,
                    'addPoints' => $item->addPoints,
                    'salePoints' => $item->salePoints,
                    'discountFlg' => $item->discountFlg,
                    'pointsByFlg' => $item->pointsByFlg,
                    'brandID' => $item->brandID,
                    'brandName' => $item->brandName,
                    'unitID' => $item->unitID,
                    'unitName' => $item->unitName,
                    'brief' => $item->brief,
                    'description' => $item->description,
                    'goodsMainPic' => $this->setImgLink($item->goodsMainPic),
                    'img_link' => $this->setImgLink($item->goodsMainPic),
                    'memo' => $item->memo,
                    'goodsLength' => $item->goodsLength,
                    'goodsWidth' => $item->goodsWidth,
                    'goodsHeight' => $item->goodsHeight,
                    'goodsWeight' => $item->goodsWeight,
                    'barcode' => $item->barcode,
                    'product_code' => $item->product_code,
                    'twoPostID' => $item->twoPostID,
                    'product_mainID' => $item->product_mainID,
                    'site_id' => $item->site_id,
                    'uid' => $item->uid,
                    'link' => $this->setLink( $item->uid ),
                    'wap_link' => $this->setWapLink( $item->uid ),
                    'bigCategoryLink' => $this->setCategoryLink($item->bigCategoryID),
                    'midCategoryLink' => $this->setCategoryLink($item->bigCategoryID, $item->midCategoryID),
                    'smallCategoryLink' => $this->setCategoryLink($item->bigCategoryID, $item->midCategoryID, $item->smallCategoryID),
                );
            }

            if (isset($arg_array['postID']) || isset($arg_array['product_code'])) {
                return $item_array[0];
            } else {
                return $item_array;
            }

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }


    /**
     * 根据会员等级计算商品价格及积分，同时查询商品促销活动
     * @param array $customer_array 会员信息数组
     * @param array $goods_array 商品数组
     * @param object $promotionHandler 促销活动类
     */
    public function shopCalculationGoodsPrice( $cust_rank, &$goods_array, &$promotionHandler ) {

        /**
         * ==========================
         * 根据会员等级计算商品价格及积分
         * ==========================
         */
        if ($cust_rank['discount_flg'] == 1)
            $goods_array['price'] = round($goods_array['salePrice'] * $cust_rank['rate'], 2);
        else
            $goods_array['price'] = round($goods_array['marketPrice'] * $cust_rank['rate'], 2);
        $goods_array['salePoints'] = round($goods_array['salePoints'] * $cust_rank['pointsRate']);


        /**
         * ==========================
         * 查询商品促销活动
         * ==========================
         */
        $p_arg_array = array(
            'datetime' => date(G_DEFAULT_DATETIME_FORMAT),
            'postID' => $goods_array['postID']
        );
        $promotion_array = $promotionHandler->searchGoodsPromotion($p_arg_array);
        if ($promotion_array) {
            foreach($promotion_array as &$p) {
                if ($p['type'] == 1) {
                	
                	//立减商品
                    $goods_array['price'] -= $p['money'];
                    
                } else if ($p['type'] == 2) {
                	
                	//特价商品
                    $goods_array['price'] = $p['money'];
                    $goods_array['goods_from'] = 2;
                    
                } else if ($p['type'] == 4) {
                	
                	//积分加倍
                    $goods_array['goods_points'] = $goods_array['goods_points'] * $p['points'];
                }
                
                //价格小于0均设为0
                if ( $goods_array['price'] <= 0 ) {
                	$goods_array['price'] = 0;
                }
            }
            $goods_array['promotion'] = $promotion_array;
        } else {
            $goods_array['promotion'] = null;
        }

    }

	/**
	 * 生成商品详情页链接地址
	 * @author 刘道健 hfldj@126.com 
	 * @param int $id 商品网购号
	 * @return $url_link 商品详情页链接地址
	 */
	public function setLink( $id ) {
		return G_WEBSITE_DOMAINNAME . '/shop/goods-' . $id . '.html';
	}


    /**
     * 生成手机商品详情页链接地址
     * @author 刘道健 hfldj@126.com
     * @param int $id 商品网购号
     * @return $url_link 商品详情页链接地址
     */
    public function setWapLink( $id ) {
        return G_WEBSITE_DOMAINNAME . '/wap/goods-' . $id . '.html';
    }




    public function setCategoryLink( $bigID, $midID = '', $smallID = '' ) {
        return G_WEBSITE_DOMAINNAME . sprintf('/shop/list-%d%s%s.html', $bigID, $midID, $smallID);
    }


    /**
     * 检查商品库存
     * @param int $goodsID 商品号
     * @param int $goods_amount 商品数量
     * @return int
     */
    public function checkGoodsStore( $goodsID, $goods_amount ) {

        $store_obj = new entity('wms_goodsstore');
        $store_obj->goodsID = $goodsID;
        if (!$this->dbca->fetch($store_obj))
            return 0;
        if ($store_obj->enableSaleAmount < $goods_amount)
            return 0;

        return 1;

    }

    /**
     * 查询商品库存
     * @param int $goodsID 商品号
     * @return int
     */
    public function searchGoodsStore($goodsID ) {
        $store_obj = new entity('wms_goodsstore');
        $store_obj->goodsID = $goodsID;
        if (!$this->dbca->fetch($store_obj)) {
            return 0;
        }
        return $store_obj->enableSaleAmount;
    }
	
	/**
	 * 生成商品图片地址
	 * @author 刘道健 hfldj@126.com 
	 * @param string $val 商品图片地址或网购号
	 * @param object $dbca 数据库实例，默认为空
	 * @return 商品图片链接地址
	 */
	public function setImgLink( $val ) {
        return G_IMAGE_URL . '/goods/' . $val;
	}

    /**
     * 查询商品颜色规格
     * @param resources $product_mainID 外部商品主编号
     * @return array|null
     */
    public function searchColorSpec( $product_mainID ) {

        if (!isset($product_mainID) || empty($product_mainID))
            return null;

        //查询语句
        $search_sql = 'SELECT gl.*,gsr.specName,gsr.spec_sortOrder,gsr.specID,gsr.specGroupName FROM goods_list gl
                       INNER JOIN goods_spec_relation gsr ON gsr.goodsID = gl.goodsID
                       WHERE gl.product_mainID = ?';

        //查询主商品下的不同颜色的商品
        $temp_goods_array = $this->dbca->stmt_query($search_sql, 's', $product_mainID);
        if (!$temp_goods_array)
            return null;


        foreach($temp_goods_array as &$goods_obj) {
            $goods_array[] = array(
                'id' => $goods_obj->postID,
                'uid' => $goods_obj->uid,
                'goodsName' => $goods_obj->goodsName,
                'specName' => $goods_obj->specName,
                'specGroupName' => $goods_obj->specGroupName,
                'imgLink' => $this->setImgLink($goods_obj->goodsMainPic),
                'link' => $this->setLink($goods_obj->uid),
                'wap_link' => $this->setWapLink($goods_obj->uid)
            );
        }

		return $goods_array;

	}


    /**
     * 查询商品尺码规格
     * @param int $twoPostID 二级网购号
     * @param int $storeID 库存ID
     * @return array|null
     */
    public function searchSizeSpec( $twoPostID, $storeID = null ) {

        if (!isset($twoPostID) || !is_numeric($twoPostID))
            return null;

        ////查询主商品下的不同颜色的商品
        $search_sql = 'SELECT gsr.specID,gsr.specGroup_sortOrder,gsr.specName,gsr.specGroupName,gl.*,wgs.enableSaleAmount FROM goods_spec_relation gsr
					       INNER JOIN goods_sale gl ON  gl.goodsID = gsr.goodsID
					       INNER JOIN wms_goodsstore wgs ON gl.goodsID = wgs.goodsID
					       WHERE gsr.twoPostID = ?';
        $temp_goods_array = $this->dbca->stmt_query($search_sql, 'i', $twoPostID);

        if (!$temp_goods_array)
            return null;

        foreach($temp_goods_array as &$goods_obj) {
            $goods_array[] = array(
                'goodsID' => $goods_obj->goodsID,
                'postID' => $goods_obj->postID,
                'goodsName' => $goods_obj->goodsName,
                'specName' => $goods_obj->specName,
                'specGroupName' => $goods_obj->specGroupName,
                'link' => $this->setLink($goods_obj->postID),
                'enableSaleAmount' => isset($goods_obj->enableSaleAmount) ? $goods_obj->enableSaleAmount : 0,
                'salePrice' => $goods_obj->salePrice,
                'product_code' => $goods_obj->product_code,
                'forsale' => $goods_obj->forsale,
                'useFlg' => $goods_obj->useFlg,
                'discountFlg' => $goods_obj->discountFlg,
                'marketPrice' => $goods_obj->marketPrice,
                'salePoints' => $goods_obj->salePoints,
                'pointsByFlg' => $goods_obj->pointsByFlg,
                'pointPrice' => $goods_obj->pointPrice,
                'addPoints' => $goods_obj->pointsByFlg ? $goods_obj->addPoints : 0
            );
        }

        return $goods_array;

    }


    /**
     * 商品分类列表
     * @param int $big_category_id 大分类号
     * @param int $middle_category_id 中分类号
     * @param int $small_category_id 小分类号
     * @return array|null
     */
    public function categoryList( $big_category_id = 0, $middle_category_id = 0, $small_category_id = 0 ) {

        //分类数组
        $category_array = array();

        /**
         * =====================================
         * 大分类
         * =====================================
         */

        if ($big_category_id == 0) {

            //查询所有大分类
            $search_sql = 'SELECT bigCategoryID,description AS bigTitle FROM goods_bigcategory WHERE useFlg = 1 ORDER BY sortOrder ASC';
            $big_category_array = $this->dbca->stmt_query($search_sql);

        } else {

            //查询指定的大分类
            $search_sql = 'SELECT bigCategoryID,description AS bigTitle FROM goods_bigcategory WHERE bigCategoryID = ? AND useFlg = 1';
            $big_category_array = $this->dbca->stmt_query($search_sql, 'i', $big_category_id);

        }
		if (!$big_category_array) {
            return $category_array;
        }

		foreach ($big_category_array as &$big) {

            $bigC = array (
				'mid' => array(),
				'text' => $big->bigTitle,
				'link' => sprintf('/shop/list-%s.html', $big->bigCategoryID),
			);

            /**
             * ==========================
             * 中分类
             * ==========================
             */

            if ($big_category_id > 0 && $middle_category_id > 0) {

                //查询指定的中分类
                $search_sql = 'SELECT bigCategoryID,midCategoryID,description AS midTitle FROM goods_midcategory WHERE midCategoryID = ? AND useFlg = 1';
                $mid_category_array = $this->dbca->stmt_query($search_sql, 'i', $middle_category_id);

            } else {

                //根据大分类，查询大分类下的中分类
                $search_sql = 'SELECT bigCategoryID,midCategoryID,description AS midTitle FROM goods_midcategory  WHERE bigCategoryID = ? AND useFlg = 1 ORDER BY sortOrder ASC';
                $mid_category_array = $this->dbca->stmt_query($search_sql, 'i', $big->bigCategoryID);

            }
            if (!$mid_category_array) {
                continue;
            }

            foreach ($mid_category_array as &$mid) {

                $midC = array(
                    'small' => array(),
                    'text' => $mid->midTitle,
                    'link' => sprintf('/shop/list-%s.html', $mid->bigCategoryID . $mid->midCategoryID)
                );


                /**
                 * ==========================
                 * 小分类
                 * ==========================
                 */
                if ($big_category_id > 0 && $middle_category_id > 0 && $small_category_id > 0) {

                    //查询指定的小分类
                    $search_sql = 'SELECT bigCategoryID,midCategoryID,smallCategoryID,description AS smallTitle FROM goods_smallcategory
                                   WHERE smallCategoryID = ? AND midCategoryID = ? AND useFlg=1';
                    $small_category_array = $this->dbca->stmt_query($search_sql, 'ii', $small_category_id, $middle_category_id);

                } else {

                    //查询中分类下的所有小分类
                    //查询指定的小分类
                    $search_sql = 'SELECT bigCategoryID,midCategoryID,smallCategoryID,description AS smallTitle FROM goods_smallcategory WHERE midCategoryID = ? AND useFlg=1 ORDER BY sortOrder ASC';
                    $small_category_array = $this->dbca->stmt_query($search_sql, 'i', $mid->midCategoryID);

                }
                
                if ($small_category_array) {
                    //生成小分类数组
	                foreach ($small_category_array as &$small) {
	                    $smallC = array(
	                        'text' => $small->smallTitle,
	                        'link' => sprintf('/shop/list-%s.html', $small->bigCategoryID . $small->midCategoryID . $small->smallCategoryID)
	                    );
	                    $smallC['text'] = $small->smallTitle;
	                    $smallC['link'] = '/shop/list-' . $small->bigCategoryID . $small->midCategoryID . $small->smallCategoryID . '.html';
	                    $midC['small'][ $small->smallCategoryID] = $smallC;
	                }
                }
				
                $bigC['mid'][$mid->midCategoryID] = $midC;

            }

            $category_array[$big->bigCategoryID] = $bigC;

		}

		return $category_array;

	}

    /**
     * 手机端商品分类列表
     * @param int $big_category_id 大分类ID
     * @param int $middle_category_id 中分类ID
     * @param int $small_category_id 小分类ID
     * @return array|int
     */
    public function categoryWapList( $big_category_id = 0, $middle_category_id = 0, $small_category_id = 0 ) {
		
		//生成分类表名称
		$table_big = 'goods_bigcategory';
		$table_mid = 'goods_midcategory';
		$table_small = 'goods_smallcategory';

		$sql = '';

		//如果扩展信息里有大分类ID，则查询分类时只查询该大分类信息
		if ($big_category_id > 0)
            $sql .= 'bigCategoryID = ' . $big_category_id . ' AND ';

		//查询所有大分类
		$categoryList = array();
		$search_sql = 'SELECT bigCategoryID,description AS bigTitle FROM ' . $table_big . ' WHERE ' . $sql. 'useFlg = 1 ORDER BY sortOrder ASC';
		$big_list = $this->dbca->stmt_query($search_sql);
		if (!$big_list)
			return -1;

		//生成大分类数组
		foreach ($big_list as &$big) {		
			$bigC = array ( 
				'mid' => array(),
				'text' => $big->bigTitle,
				'link' => '/wap/category-' . $big->bigCategoryID . '.html?emt=0.0.3.15.'.$big->bigCategoryID.'.'.$big->bigCategoryID
			);
			$categoryList[$big->bigCategoryID] = $bigC;
		}

		//查询所有中分类
		if ($sql == '') {

			//查询所有中分类
            $search_sql = 'SELECT bigCategoryID,midCategoryID,description AS midTitle FROM ' . $table_mid . '  WHERE useFlg = 1';

		} else if ($middle_category_id > 0) {

			//根据中分类ID查询单个中分类
            $search_sql = 'SELECT bigCategoryID,midCategoryID,description AS midTitle FROM ' . $table_mid .
					      '  WHERE midCategoryID = ' . $middle_category_id . ' AND useFlg = 1';
			$sql .= 'midCategoryID = ' . $middle_category_id . ' AND ';

		} else {

			//根据大分类ID，查询该大分类下的所有中分类
            $search_sql = 'SELECT bigCategoryID,midCategoryID,description AS midTitle FROM ' . $table_mid . '  WHERE ' . $sql . 'useFlg = 1';

		}
		$mid_list = $this->dbca->stmt_query($search_sql);
		if (!$mid_list)
			return $categoryList;
			
		//生成中分类数组
		foreach ($mid_list as &$mid) {
			if (!isset($categoryList[$mid->bigCategoryID]))
				continue;
			$midC['small'] = array();
			$midC['text'] = $mid->midTitle;
			$midC['link'] = '/wap/category-' . $mid->bigCategoryID . $mid->midCategoryID . '.html?emt=0.0.3.15.'.$mid->bigCategoryID . $mid->midCategoryID.'.'.$mid->bigCategoryID . $mid->midCategoryID;
			$categoryList[$mid->bigCategoryID]['mid'][$mid->midCategoryID] = $midC;
		}
		

		//查询小分类
		if ($sql == '') {

			//查询所有小分类
            $search_sql = 'SELECT bigCategoryID,midCategoryID,smallCategoryID,description AS smallTitle FROM ' . $table_small . ' WHERE useFlg=1';

		} else if ($small_category_id > 0) {

			//根据小分类查询单个小分类信息
            $search_sql = sprintf('SELECT bigCategoryID,midCategoryID,smallCategoryID,description AS smallTitle FROM ' . $table_small . '
							   WHERE smallCategoryID = %d AND midCategoryID = %d AND useFlg=1', $small_category_id, $middle_category_id);

		} else {

			//根据大分类ID，查询该大分类下的所有中分类
            $search_sql = 'SELECT bigCategoryID,midCategoryID,description AS smallTitle FROM ' . $table_small . '  WHERE ' . $sql . 'useFlg = 1';

		}

		$small_list = $this->dbca->stmt_query($search_sql);
		if (!$small_list)
			return $categoryList;
		
		//生成小分类数组
		foreach ($small_list as &$small) {
			$smallC['text'] = $small->smallTitle;
			$smallC['link'] = '/wap/list-' . $small->bigCategoryID . $small->midCategoryID . $small->smallCategoryID . '.html?emt=0.0.3.15.'.$small->bigCategoryID . $small->midCategoryID . $small->smallCategoryID.'.'.$small->bigCategoryID . $small->midCategoryID . $small->smallCategoryID;
			$categoryList[$small->bigCategoryID]['mid'][$small->midCategoryID]['small'][ $small->smallCategoryID] = $smallC;
		}

		//返回值
		return $categoryList;

	}

	/**
     * 添加分类
     *
     * @param unknown_type $arg_array
     * @return unknown
     */
	public function saveCategory( $arg_array ){
		
		//参数检查
		if (!isset( $arg_array['params'] , $arg_array['params'])) {
			return array( 'code' => 400, 'message' => '参数错误');
		}
		
		if (isset($arg_array['params']['categoryID']) && !empty($arg_array['params']['categoryID'])) {	//编辑
			$editArray = explode('_', $arg_array['params']['categoryID']);
			switch ($editArray[1]) {
				case 1:	//编辑大分类
					$edit_category = new entity('goods_bigcategory');
					$edit_category->bigCategoryID = $editArray[0];
					
					//检查分类名称是否重复
					$check_categoryName = new entity('goods_bigcategory');
					
					//标签组
					$tagGroupID = BIGCATEGORY_TAGGROUPID;
					
					//更新商品里面的分类名称
					$goods_list = sprintf('UPDATE goods_list SET TIMESTAMP=NOW(), bigCategoryName="%s" WHERE bigCategoryID=%d', $arg_array['params']['categoryName'], $editArray[0]);
					$goods_list_edit = sprintf('UPDATE goods_list_edit SET TIMESTAMP=NOW(), bigCategoryName="%s" WHERE bigCategoryID=%d', $arg_array['params']['categoryName'], $editArray[0]);
					$goods_sale = sprintf('UPDATE goods_sale SET TIMESTAMP=NOW(), bigCategoryName="%s" WHERE bigCategoryID=%d', $arg_array['params']['categoryName'], $editArray[0]);
					$goods_sale_edit = sprintf('UPDATE goods_sale_edit SET TIMESTAMP=NOW(), bigCategoryName="%s" WHERE bigCategoryID=%d', $arg_array['params']['categoryName'], $editArray[0]);
					
				break;
				case 2:	//编辑中分类
					$edit_category = new entity('goods_midcategory');
					$edit_category->midCategoryID = $editArray[0];
					
					$check_categoryName = new entity('goods_midcategory');
					
					$tagGroupID = MIDCATEGORY_TAGGROUPID;
					
					//更新商品里面的分类名称
					$goods_list = sprintf('UPDATE goods_list SET TIMESTAMP=NOW(), midCategoryName="%s" WHERE midCategoryID=%d', $arg_array['params']['categoryName'], $editArray[0]);
					$goods_list_edit = sprintf('UPDATE goods_list_edit SET TIMESTAMP=NOW(), midCategoryName="%s" WHERE midCategoryID=%d', $arg_array['params']['categoryName'], $editArray[0]);
					$goods_sale = sprintf('UPDATE goods_sale SET TIMESTAMP=NOW(), midCategoryName="%s" WHERE midCategoryID=%d', $arg_array['params']['categoryName'], $editArray[0]);
					$goods_sale_edit = sprintf('UPDATE goods_sale_edit SET TIMESTAMP=NOW(), midCategoryName="%s" WHERE midCategoryID=%d', $arg_array['params']['categoryName'], $editArray[0]);

				break;
				case 3:	//编辑小分类
					$edit_category = new entity('goods_smallcategory');
					$edit_category->smallCategoryID = $editArray[0];
					
					$check_categoryName = new entity('goods_smallcategory');
					
					$tagGroupID = SMALLCATEGORY_TAGGROUPID;
					
					//更新商品里面的分类名称
					$goods_list = sprintf('UPDATE goods_list SET TIMESTAMP=NOW(), smallCategoryName="%s" WHERE smallCategoryID=%d', $arg_array['params']['categoryName'], $editArray[0]);
					$goods_list_edit = sprintf('UPDATE goods_list_edit SET TIMESTAMP=NOW(), smallCategoryName="%s" WHERE smallCategoryID=%d', $arg_array['params']['categoryName'], $editArray[0]);
					$goods_sale = sprintf('UPDATE goods_sale SET TIMESTAMP=NOW(), smallCategoryName="%s" WHERE smallCategoryID=%d', $arg_array['params']['categoryName'], $editArray[0]);
					$goods_sale_edit = sprintf('UPDATE goods_sale_edit SET TIMESTAMP=NOW(), smallCategoryName="%s" WHERE smallCategoryID=%d', $arg_array['params']['categoryName'], $editArray[0]);
					
				break;
				default:
					return array( 'code' => 400, 'message' => '参数错误');
				break;		
			}
			
			if (!$this->dbca->fetch($edit_category)) {
				return array( 'code' => 400, 'message' => sprintf('分类号「%s」信息未找到，请核实', $editArray[0]));
			}

			//检查名字分类名是否重复
			$check_categoryName->description = $arg_array['params']['categoryName'];
			$is_categoryName = $this->dbca->fetch($check_categoryName);
			
			switch ($editArray[1]) {
				case 1:
//					if ($is_categoryName && $check_categoryName->bigCategoryID != $editArray[0]) {
//						return array( 'code' => 400, 'message' => sprintf('分类名称「%s」已经存在', $arg_array['params']['categoryName']));
//					}
					
					$mappingID = $edit_category->bigCategoryID;
					
					$changeID = $edit_category->bigCategoryID;
				break;
				case 2:
//					if ($is_categoryName && $check_categoryName->midCategoryID != $editArray[0]) {
//						return array( 'code' => 400, 'message' => sprintf('分类名称「%s」已经存在', $arg_array['params']['categoryName']));
//					}
					$mappingID = $edit_category->bigCategoryID . $edit_category->midCategoryID;
					
					$changeID = $edit_category->midCategoryID;
				break;
				case 3:
//					if ($is_categoryName && $check_categoryName->smallCategoryID != $editArray[0]) {
//						return array( 'code' => 400, 'message' => sprintf('分类名称「%s」已经存在', $arg_array['params']['categoryName']));
//					}
					
					$mappingID = $edit_category->bigCategoryID . $edit_category->midCategoryID . $edit_category->smallCategoryID;
					$changeID = $edit_category->smallCategoryID;
				break;	
			}
			
			
			//修改标签名称
//			$tag_array = array(
//				'tagName'	 => $arg_array['params']['categoryName'] ,
//				'tagID'		 => $edit_category->tagID ,
//				'tagGroupID' => $tagGroupID ,
//				'creator' 	 => $arg_array['creator']
//			) ;
//							    
//			$resultData = $this->commPropertyTag ( $tag_array ) ;	
//			if($resultData['code'] == 400) {
//				return array( 'code' => 400, 'message' => $resultData['message']);
//			}	
				
			$edit_category->description = $arg_array['params']['categoryName'];
			$edit_category->editor      = $arg_array['creator'];
			$edit_category->tagID       = 0;

		} else {	//添加
			
			$addArray = explode('_', $arg_array['params']['parentID']);
			
			switch ($addArray[2]) {
				
				case 1:	//添加大分类
				
					$save_category = new entity('goods_bigcategory');
					
					//最大排序
					$maxSort = $this->dbca->stmt_query('SELECT MAX(sortOrder)+1 maxSort FROM goods_bigcategory');
				
					//检查分类名称是否重复
					$check_categoryName = new entity('goods_bigcategory');
					
					//标签组
					$tagGroupID = BIGCATEGORY_TAGGROUPID;
					
					//最大分类ID
					$max_sql = 'SELECT MAX(bigCategoryID) maxID FROM goods_bigcategory';
					
				break;	
				case 2:	//添加中分类
				
					$save_category = new entity('goods_midcategory');
					$save_category->bigCategoryID = $addArray[0];
					
					//最大排序
					$maxSort = $this->dbca->stmt_query('SELECT MAX(sortOrder)+1 maxSort FROM goods_midcategory');
				
					$check_categoryName = new entity('goods_midcategory');
					
					$tagGroupID = MIDCATEGORY_TAGGROUPID;
					
					$mappingID = $addArray[0];
					
					//最大分类ID
					$max_sql = 'SELECT MAX(midCategoryID) maxID FROM goods_midcategory';
				break;	
				case 3:	//添加小分类
				
					$save_category = new entity('goods_smallcategory');
					$save_category->bigCategoryID = $addArray[0];
					$save_category->midCategoryID = $addArray[1];
					
					//最大排序
					$maxSort = $this->dbca->stmt_query('SELECT MAX(sortOrder)+1 maxSort FROM goods_smallcategory');
				
					$check_categoryName = new entity('goods_smallcategory');
					
					$tagGroupID = SMALLCATEGORY_TAGGROUPID;
					
					$mappingID = $addArray[0] . $addArray[1];
					
					//最大分类ID
					$max_sql = 'SELECT MAX(smallCategoryID) maxID FROM goods_smallcategory';
					
				break;
				default:
					return array( 'code' => 400, 'message' => '参数错误');
				break;	
			}
			
			//检查分类名称是否重复
//			$check_categoryName->description = $arg_array['params']['categoryName'];
//			if ($this->dbca->fetch($check_categoryName)) {
//				
//				if ($addArray[2] == 1) {
//					
//					return array( 'code' => 400, 'message' => sprintf('分类名称「%s」已经存在', $arg_array['params']['categoryName']));
//					
//				} else if($addArray[2] == 2) {
//					if ($check_categoryName->bigCategoryID == $addArray[0]) {
//						return array( 'code' => 400, 'message' => sprintf('分类名称「%s」已经存在', $arg_array['params']['categoryName']));
//					}
//					
//				} else if($addArray[2] == 3) {
//					if ($check_categoryName->bigCategoryID == $addArray[0] && $check_categoryName->midCategoryID == $addArray[1]) {
//						return array( 'code' => 400, 'message' => sprintf('分类名称「%s」已经存在', $arg_array['params']['categoryName']));
//					}
//				}
//			}
			
			//标签
//			$tag_array = array(
//				'tagName'	 => $arg_array['params']['categoryName'] ,
//				'tagID'		 => 0 ,
//				'tagGroupID' => $tagGroupID ,
//				'creator' 	 => $arg_array['creator']
//			) ;
//			$resultData = $this->commPropertyTag ($tag_array) ;
			
			$save_category->creator     = $arg_array['creator'];
			$save_category->description = $arg_array['params']['categoryName'];
			$save_category->tagID       = 0;
			$save_category->useFlg      = 1;
			$save_category->sortOrder   = $maxSort[0]->maxSort;
			
		}
		
		$this->dbca->beginTransaction();
		try {
			if (isset($arg_array['params']['categoryID']) && !empty($arg_array['params']['categoryID'])){
				$this->dbca->save($edit_category);
	
				$this->dbca->stmt_query($goods_list);
				$this->dbca->stmt_query($goods_list_edit);
				$this->dbca->stmt_query($goods_sale);
				$this->dbca->stmt_query($goods_sale_edit);
				
				$data = array(
					'categoryName' => $arg_array['params']['categoryName'],
					'categoryID'   => isset($changeID) ? $changeID : 0,
					'type'		   => 2
				);
			} else {
				$this->dbca->save($save_category);
				
				$maxID = $this->dbca->stmt_query($max_sql);
				if (!isset($mappingID) || empty($mappingID)) {
					$mappingID = $maxID[0]->maxID;
				} else {
					$mappingID .= $maxID[0]->maxID;
				}
				
				$data = array('type' => 1);
				
			}
			
			//添加规格组、标签组对应关系
			if (isset($arg_array['params']['specGroupID'])) {
				//删除旧的对应关系
				$this->dbca->stmt_query('DELETE FROM goods_category_specGroup WHERE categoryID = ?', 's', $mappingID);
				
				foreach ($arg_array['params']['specGroupID'] as $specGroupID) {
					$goods_category_specGroup = new entity('goods_category_specGroup');
					$goods_category_specGroup->creator     = $arg_array['creator'];
					$goods_category_specGroup->categoryID  = $mappingID;
					$goods_category_specGroup->specGroupID = $specGroupID;
					
					$this->dbca->save($goods_category_specGroup);
				}
			}
			
			if (isset($arg_array['params']['groupID'])) {
				//删除旧的对应关系
				$this->dbca->stmt_query('DELETE FROM goods_category_tagGroup WHERE categoryID = ?', 's', $mappingID);
				
				foreach ($arg_array['params']['groupID'] as $tagGroupID) {
					$goods_category_tagGroup = new entity('goods_category_tagGroup');
					$goods_category_tagGroup->creator     = $arg_array['creator'];
					$goods_category_tagGroup->categoryID  = $mappingID;
					$goods_category_tagGroup->tagGroupID  = $tagGroupID;
					
					$this->dbca->save($goods_category_tagGroup);
				}
			}
			
			$this->dbca->commit();
			if (isset($arg_array['params']['categoryID']) && !empty($arg_array['params']['categoryID'])){
				return array( 'code' => 200, 'message' => '商品分类更新成功', 'data' => $data);
			} else {
				return array( 'code' => 200, 'message' => '商品分类保存成功', 'data' => $data);
			}
			
		}catch(Exception $e){
			error_log($e->getMessage());
			$this->dbca->rollBack();
			if (isset($arg_array['params']['categoryID']) && !empty($arg_array['params']['categoryID'])){
				return array( 'code' => 400, 'message' => '商品分类更新失败');
			} else {
				return array( 'code' => 400, 'message' => '商品分类保存失败');
			}
		}	
	}
	
	
	
	/**
	 * 获得分类列表
	 * @param $arg_array 参数数组
	 */
	public function searchCategory(&$arg_array){
		$sql 		  = '';
		$params_type  = '';
		$params_array = array();
		if(isset($arg_array['description']) && !empty($arg_array['description'])){
			$sql .= ' AND gb.description LIKE ?';
			$params_type .= 's';
			$params_array[] = '%' . trim($arg_array['description']) . '%';
		}	
		
		if(!empty($sql))
			$sql =' WHERE ' . substr($sql, 4);
		
		//分类信息查询
		$search_sql = 'SELECT DISTINCT gs.smallCategoryID g_id,gs.description g_desc,gs.useFlg g_use,gs.sortOrder g_sort,gm.description gm_desc,
			gm.midCategoryID gm_id,gm.useFlg gm_use,gm.sortOrder gm_sort, gb.bigCategoryID gb_id,gb.description gb_desc,
			gb.useFlg gb_use,gb.sortOrder gb_sort FROM goods_smallcategory gs
			RIGHT JOIN goods_midcategory gm FORCE INDEX (PRIMARY) ON gm.midCategoryID = gs.midCategoryID
			RIGHT JOIN goods_bigcategory gb FORCE INDEX (PRIMARY) ON gb.bigCategoryID = gm.bigCategoryID
			'.$sql.'
			ORDER BY gb.bigCategoryID,gm.midCategoryID,gs.smallCategoryID ';
		
		$search_info = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
		if($search_info){
			$bigArray   = array () ;
			$midArray 	= array ()	;
			$smallArray = array () ;
			$bigID 	 = 0 ;
			$midID 	 = 0 ;
			foreach ($search_info as &$temp_l) {
				if($midID != $temp_l->gm_id && $midID != 0){	
					$midArray[$midID]['small']= $smallArray;
					$smallArray = array () ;
				}
				
				if($bigID != $temp_l->gb_id && $bigID != 0){	
					$bigArray[$bigID]['mid'] = $midArray;
					$midArray = array();
				}
				
				$midID = $temp_l->gm_id ;
				$smallArray[$temp_l->g_id] = array (
					'id'   => $temp_l->g_id,
					'desc' => $temp_l->g_desc,
					'use'  => $temp_l->g_use,
					'sort' => $temp_l->g_sort
				)  ;
		
				$bigID = $temp_l->gb_id ;
				if(!array_key_exists($temp_l->gm_id , $midArray)) {
					$midArray[$temp_l->gm_id] = array(
						'id'    => $temp_l->gm_id,
						'desc'  => $temp_l->gm_desc,
						'use'   => $temp_l->gm_use,
						'sort'  => $temp_l->gm_sort
					) ;
				}
				
				if( !array_key_exists($temp_l->gb_id, $bigArray)) {
					$bigArray[$temp_l->gb_id] = array(
						'id'   => $temp_l->gb_id,
						'desc' => $temp_l->gb_desc,
						'use'  => $temp_l->gb_use,
						'sort' => $temp_l->gb_sort,
					) ;
				}
			}
			$midArray[$midID]['small'] = $smallArray;
			$bigArray[$bigID]['mid']   = $midArray;
			
			$arg_array['count'] = count($bigArray);
			return $bigArray;
		}else 
			return null;
	}

	
	/**
	 * 删除分类
	 *
	 */
	public function deleteCategory ( $arg_array ) {
		
		//检查参数
		if (!isset($arg_array['categoryID'], $arg_array['level'])) {
			return array( 'code' => 400, 'message' => '缺少参数' );
		}
		
		if (!in_array($arg_array['level'], array(1, 2, 3))) {
			return array( 'code' => 400, 'message' => '参数错误' );
		}
		
		//检查删除的是否是子分类
		switch ($arg_array['level']) {
			case 1:	//大分类
				$goods_midcategory = new entity('goods_midcategory');
				$goods_midcategory->bigCategoryID = $arg_array['categoryID'];
				if ($this->dbca->fetch($goods_midcategory)) {
					return array( 'code' => 400, 'message' => '请先删除子分类' );
				}
				
				$goods_smallcategory = new entity('goods_smallcategory');
				$goods_smallcategory->bigCategoryID = $arg_array['categoryID'];
				if ($this->dbca->fetch($goods_smallcategory)) {
					return array( 'code' => 400, 'message' => '请先删除子分类' );
				}
				
				//检查分类是否存在商品
				$goods_list      = sprintf('SELECT * FROM goods_list WHERE bigCategoryID = %s', $arg_array['categoryID']);
				$goods_list_edit = sprintf('SELECT * FROM goods_list_edit WHERE bigCategoryID = %s', $arg_array['categoryID']);
				$goods_sale      = sprintf('SELECT * FROM goods_sale WHERE bigCategoryID = %s', $arg_array['categoryID']);
				$goods_sale_edit = sprintf('SELECT * FROM goods_sale_edit WHERE bigCategoryID = %s', $arg_array['categoryID']);
				
				//删除分类sql
				$category_sql = sprintf('DELETE FROM goods_bigcategory WHERE bigCategoryID = %s', $arg_array['categoryID']);
				
			break;	
            case 2:	//中分类
				$goods_smallcategory = new entity('goods_smallcategory');
				$goods_smallcategory->midCategoryID = $arg_array['categoryID'];
				if ($this->dbca->fetch($goods_smallcategory)) {
					return array( 'code' => 400, 'message' => '请先删除子分类' );
				}
				
				//检查分类是否存在商品
				$goods_list      = sprintf('SELECT * FROM goods_list WHERE midCategoryID = %s', $arg_array['categoryID']);
				$goods_list_edit = sprintf('SELECT * FROM goods_list_edit WHERE midCategoryID = %s', $arg_array['categoryID']);
				$goods_sale      = sprintf('SELECT * FROM goods_sale WHERE midCategoryID = %s', $arg_array['categoryID']);
				$goods_sale_edit = sprintf('SELECT * FROM goods_sale_edit WHERE midCategoryID = %s', $arg_array['categoryID']);
				
				$category_sql = sprintf('DELETE FROM goods_midcategory WHERE midCategoryID = %s', $arg_array['categoryID']);
				
			break;	
            case 3:
           		//检查分类是否存在商品
				$goods_list      = sprintf('SELECT * FROM goods_list WHERE smallCategoryID = %s', $arg_array['categoryID']);
				$goods_list_edit = sprintf('SELECT * FROM goods_list_edit WHERE smallCategoryID = %s', $arg_array['categoryID']);
				$goods_sale      = sprintf('SELECT * FROM goods_sale WHERE smallCategoryID = %s', $arg_array['categoryID']);
				$goods_sale_edit = sprintf('SELECT * FROM goods_sale_edit WHERE smallCategoryID = %s', $arg_array['categoryID']);
				
				$category_sql = sprintf('DELETE FROM goods_smallcategory WHERE smallCategoryID = %s', $arg_array['categoryID']);	
            break;	
		}
		
		//删除的分类是否有商品
		$check_goods_list      = $this->dbca->stmt_query($goods_list);
		$check_goods_list_edit = $this->dbca->stmt_query($goods_list_edit);
		$check_goods_sale      = $this->dbca->stmt_query($goods_sale);
		$check_goods_sale_edit = $this->dbca->stmt_query($goods_sale_edit);
		
		if ($check_goods_list || $check_goods_list_edit || $check_goods_sale || $check_goods_sale_edit) {
			return array( 'code' => 400, 'message' => '当前分类存在对应的商品信息，不能删除' );
		}

		//删除分类
		$this->dbca->stmt_query($category_sql);
		
		$data = array(
			'type'       => 2,
			'categoryID' => $arg_array['categoryID']
		);
		return array( 'code' => 200, 'message' => '商品分类删除成功', 'data' => $data );
	}

    //删除分类
    public function deletecate ( $arg_array ){
        if (!isset($arg_array['delete_str']))
            return array( 'code' => 400, 'message' => '缺少参数' );

        //将字符串截成数组
        $delete_array = explode('_', $arg_array['delete_str']);
        $cate_arr = '';//存放分类ID

        try {
            //对每个数组元素进行大、中、小分类判断
            switch (count($delete_array)){
                case 1:
                    $cate_arr[] = $delete_array[0];
                    $midd_id = $this->dbca->stmt_query('select midCategoryID from goods_midcategory WHERE bigCategoryID = ? ', 'i' , array($delete_array[0]));
                    if($midd_id){
                        foreach( $midd_id as $val){
                            $cate_arr[] =  $val->midCategoryID;
                        }
                    }
                    $small_id = $this->dbca->stmt_query('select smallCategoryID from goods_smallcategory WHERE bigCategoryID = ? ', 'i' , array($delete_array[0]));
                    if($small_id){
                        foreach( $small_id as $val){
                            $cate_arr[] =  $val->smallCategoryID;
                        }
                    }
                    //删除大分类，需要删除对应的中分类和小分类
                    $this->dbca->stmt_query(sprintf('DELETE FROM goods_bigcategory WHERE bigCategoryID = %s', $delete_array[0]));
                    $this->dbca->stmt_query(sprintf('DELETE FROM goods_midcategory WHERE bigCategoryID = %s', $delete_array[0]));
                    $this->dbca->stmt_query(sprintf('DELETE FROM goods_smallcategory WHERE bigCategoryID = %s', $delete_array[0]));

                    break;
                case 2:
                    //删除中分类，需要删除中分类对应的小分类
                    $cate_arr[] = $delete_array[1];
                    $small_id = $this->dbca->stmt_query('select smallCategoryID from goods_smallcategory WHERE bigCategoryID = ? AND midCategoryID = ?', 'ii' , array($delete_array[0], $delete_array[1]));
                    if($small_id){
                        foreach( $small_id as $val){
                            $cate_arr[] =  $val->smallCategoryID;
                        }
                    }

                    $this->dbca->stmt_query(sprintf('DELETE FROM goods_midcategory WHERE bigCategoryID = %s AND midCategoryID = %s', $delete_array[0], $delete_array[1]));
                    $this->dbca->stmt_query(sprintf('DELETE FROM goods_smallcategory WHERE bigCategoryID = %s AND midCategoryID = %s', $delete_array[0], $delete_array[1]));
                    break;
                case 3:	//小分类
                    $cate_arr[] = $delete_array[2];
                    $this->dbca->stmt_query(sprintf('DELETE FROM goods_smallcategory WHERE bigCategoryID = %s AND midCategoryID = %s AND smallCategoryID = %s', $delete_array[0], $delete_array[1],$delete_array[2]));

                    break;
            }


            return array( 'code' => 200, 'message' => '分类删除成功','cate_arr'=>$cate_arr );

        } catch (Exception $e) {
            error_log($e->getMessage());
            return array( 'code' => 500, 'message' => '系统错误' );
        }
    }
	
	/**
	 * 根据大分类获取二级分类信息
	 *
	 */
	public function getMidCategory( $arg_array ){
		//检查参数
		if (!isset($arg_array['bigID']) || !is_numeric($arg_array['bigID']))
            return array( 'code' => 400, 'message' => '参数错误' );
            
		$midData = $this->dbca->stmt_query(sprintf('SELECT midCategoryID,description FROM goods_midcategory WHERE bigCategoryID = %s', $arg_array['bigID']));
		if($midData){
			$midArray = array();
			foreach ($midData as $val){
				$midArray[$val->midCategoryID] = $val->description;
			}
			
			return $midArray;
		}else
        	return null;
	}
	

	
	/**
     * 分类的使用和禁用
     *
     * @param unknown_type $arg_array
     * @return unknown
     */
    public function isusecategory ( $arg_array ) {
    	
        //检查参数
        if (!isset($arg_array['useFlg_str']) || $arg_array['useFlg_str'] == '')
            return array('code' => 400, 'message' => '缺少参数' );
            
        $str_array = explode('_', $arg_array['useFlg_str']);
        switch (count($str_array)){
            case 2:	//大分类
                $bigCate = new entity('goods_bigcategory');
                $bigCate->bigCategoryID = $str_array[0];
                if(!$this->dbca->fetch($bigCate))
                    return array('code' => 400, 'message' => sprintf('商品大分类号「%d」信息未找到，请核实',$str_array[0]));

                $bigCate->useFlg = $str_array[1];
                $this->dbca->save($bigCate, 'goods');
                if ($str_array[1] == 1) {
                	return array('code' => 200, 'message' => sprintf('商品大分类「%s」启用成功', $bigCate->description));
                } else {
                	return array('code' => 200, 'message' => sprintf('商品大分类「%s」禁用成功', $bigCate->description));
                }
                break;
            case 3:	//中分类
                $midCate = new entity('goods_midcategory');
                $midCate->bigCategoryID = $str_array[0];
                $midCate->midCategoryID = $str_array[1];
                if(!$this->dbca->fetch($midCate))
                    return array('code' => 400, 'message' => sprintf('商品中分类号「%d」信息未找到，请核实',$str_array[1]));

                $midCate->useFlg = $str_array[2];
                $this->dbca->save($midCate, 'goods');
                if ($str_array[2] == 1) {
                	return array('code' => 200, 'message' => sprintf('商品中分类「%s」启用成功', $midCate->description));
                } else {
                	return array('code' => 200, 'message' => sprintf('商品中分类「%s」禁用成功', $midCate->description));
                }
                
                break;
            case 4:	//小分类
                $smallCate = new entity('goods_smallcategory');
                $smallCate->bigCategoryID   = $str_array[0];
                $smallCate->midCategoryID   = $str_array[1];
                $smallCate->smallCategoryID = $str_array[2];

                if(!$this->dbca->fetch($smallCate))
                    return array('code' => 400, 'message' => sprintf('商品小分类号「%d」信息未找到,请核实',$str_array[2]));

                $smallCate->useFlg = $str_array[3];
                $this->dbca->save($smallCate, 'goods');
                if ($str_array[3] == 1) {
                	return array('code' => 200, 'message' => sprintf('商品小分类「%s」启用成功', $smallCate->description));
                } else {
                	return array('code' => 200, 'message' => sprintf('商品小分类「%s」禁用成功', $smallCate->description));
                }
                
                break;
        }

        //查询品牌是否存在或已经被操作
        $brandInfo = new entity('goods_brand');
        $brandInfo->brandID = $str_array[0] ;
        if (!$this->dbca->fetch( $brandInfo ))
            return array( 'code' => 400, 'message' => sprintf('品牌号「%d」,的品牌不存在,请审核后再操作',$str_array[0]));

        //检查品牌状态是否已经修改
        if($brandInfo->useFlg == $str_array[1] && $str_array[1] == 1)
            return array( 'code' => 400, 'message' => sprintf('品牌号「%d」,的品牌已启用',$str_array[0]));

        if($brandInfo->useFlg == $str_array[1] && $str_array[1] == 0)
            return array( 'code' => 400, 'message' => sprintf('品牌号「%d」,的品牌已禁用',$str_array[0]));

        //修改品牌状态
        $brandInfo->useFlg = $str_array[1] ;
        $this->dbca->save( $brandInfo , 'goods' );

        if($str_array[1] == 1)
            return array( 'code' => 200, 'message' => sprintf('品牌号「%d」,的品牌启用成功',$str_array[0]) );

        else if ($str_array[1] == 0)
            return array( 'code' => 200, 'message' => sprintf('品牌号「%d」,的品牌禁用成功',$str_array[0]) );
    }
	
	/**
	 * 更新商品分类使用状态
	 *
	 * @param unknown_type $arg_array
	 * @return unknown
	 */
	public function categoryUse ( $arg_array ) {
		
		//检查参数
		if (!isset($arg_array['categoryID'], $arg_array['useFlg'], $arg_array['level'])) {
            return array('code' => 400, 'message' => '缺少参数' );
		}
		
		if (!in_array($arg_array['useFlg'], array(0, 1)) || !in_array($arg_array['level'], array(1, 2, 3))) {
			return array('code' => 400, 'message' => '参数错误，请核实' );
		}
		
		//根据分类去执行对应操作
		switch ($arg_array['level']){
			case 1:	//大分类
				$change_category = new entity('goods_bigcategory');
				$change_category->bigCategoryID = $arg_array['categoryID'];
			break;	
			case 2:	//中分类
				$change_category = new entity('goods_midcategory');
				$change_category->midCategoryID = $arg_array['categoryID'];
			break;
			case 3:	//小分类
				$change_category = new entity('goods_smallcategory');
				$change_category->smallCategoryID = $arg_array['categoryID'];
			break;
		}
		
		if (!$this->dbca->fetch($change_category)) {
			return array('code' => 400, 'message' => sprintf('分类号「%d」信息未找到，请核实', $arg_array['categoryID']) );
		}
        
		$change_category->useFlg = $arg_array['useFlg'];
		
		try {
			
			$this->dbca->save($change_category);
			
			$data = array(
				'categoryID' => $arg_array['categoryID'],
				'useFlg' 	 => $arg_array['useFlg'],
				'level'		 => $arg_array['level'],
				'type'       => 1
			);
			
			return array('code' => 200, 'message' => '商品分类使用状态更新成功', 'data' => $data );
			
		}catch (Exception $e){
			
			error_log($e->getMessage());
			
			return array('code' => 400, 'message' => '商品分类使用状态更新失败' );
		}
		
	}
	
	 /**
     * 添加单位
     *
     * @param unknown_type $arg_array
     * @return unknown
     */
	public function saveUnitInfo( $arg_array ){
		//检查参数
		if (!isset($arg_array['unitName'] ,$arg_array['sortOrder'] ,$arg_array['creator'], $arg_array['useFlg'],$arg_array['unitID']))
			return array( 'code' => 400, 'message' => '参数错误');
		
		$sortOrder = $arg_array['sortOrder'] ;			//排序序号
		$unitID	   = $arg_array['unitID'] ;				//单位号
		$tagID 	   = 0 ;								
		$unitInfo  = new entity('goods_unit') ;
		$unitName   = trim($arg_array['unitName']) ;
		$this->dbca->beginTransaction();	
		try{
			//如果单位号不为空则查询检查单位号
			if($unitID != 0){
				$unitInfo->unitID = $unitID ;
				if(!$this->dbca->fetch($unitInfo))
					throw new Exception(sprintf('商品单位号「%d」信息未找到,请核实', $unitID), 400) ;
					
				//检查单位排序有没有被使用	
				$issetSO = $this->dbca->stmt_query('SELECT COUNT(*) count FROM goods_unit WHERE sortOrder=? AND unitID!=?','ii' ,$sortOrder, $unitID) ;	
				if($issetSO[0]->count > 0)
					throw new Exception(sprintf('排序序号「%d」已经被使用',$sortOrder),400) ;
						
				$unitInfo->editor = $arg_array['creator'] ;
				$tagID = $unitInfo->tagID ;
				
				//修改商品列表中的单位名称
				$this->dbca->stmt_query('UPDATE goods_list SET TIMESTAMP=NOW(), unitName=? WHERE unitID=?','si' ,$unitName, $unitID) ;
				$this->dbca->stmt_query('UPDATE goods_list_edit SET TIMESTAMP=NOW(), unitName=? WHERE unitID=?','si' ,$unitName, $unitID) ; 
				$this->dbca->stmt_query('UPDATE goods_sale SET TIMESTAMP=NOW(), unitName=? WHERE unitID=?','si' ,$unitName, $unitID) ; 
				$this->dbca->stmt_query('UPDATE goods_sale_edit SET TIMESTAMP=NOW(), unitName=? WHERE unitID=?','si' ,$unitName, $unitID) ; 
				
			}else {
				//检查单位排序有没有被使用	
				$issetSO = $this->dbca->stmt_query('SELECT COUNT(*) count FROM goods_unit WHERE sortOrder=?','i' ,$sortOrder) ;	
				if($issetSO[0]->count > 0)
					throw new Exception(sprintf('排序序号「%d」已经被使用', $sortOrder), 400) ;
					
				$unitInfo->creator = $arg_array['creator'] ;			
			}
		
			//生成单位标签
//			$tag_array  = array('tagName'	 => $unitName ,
//							    'tagID'		 => $tagID ,
//							    'tagGroupID' => UNIT_TAGGROUPID ,
//							    'creator' 	 => $arg_array['creator']) ;
//			
//			$resultData = $this->commPropertyTag ($tag_array) ;	
//			if($resultData['code'] == 400)
//				throw new Exception($resultData['message'],400) ;
	
			//保存和更新单位信息
			$unitInfo->tagID  	 = 0;
			$unitInfo->unitName  = $unitName ;
			$unitInfo->useFlg	 = $arg_array['useFlg'] ;
			$unitInfo->sortOrder = $arg_array['sortOrder'] ;
			$this->dbca->save( $unitInfo , 'goods' ) ;
			
			$this->dbca->commit();	
			
			return array( 'code' => 200, 'message' => '商品单位保存成功' );
		}catch (Exception $e) {
			$this->dbca->rollBack();
			if ($e->getCode() > 0) 
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage());
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }
		}
		
	}
	
	/**
	 * 删除单位
	 *
	 */
	public function deleteUnit ( $arg_array ) {
		
		//单位号串检查
		if (!isset($arg_array['delete_str'])) {
            return array( 'code' => 400, 'message' => '缺少参数' );
		}    

        if (empty($arg_array['delete_str'])) {
            return array( 'code' => 400, 'message' => '请选择需要删除的商品单位' );
        }    
            
		//将单位号串截成数组
        $delete_array = explode('_', $arg_array['delete_str']);
        
		$tagID_str = '' ;
        try {
        	
        	//检查单位是否存在商品
			foreach( $delete_array as &$c_l ) {
				//检查单位是否有对应商品
                $goods_list      = $this->dbca->stmt_query('SELECT * FROM goods_list WHERE unitID = ?', 'i', $c_l);
                $goods_list_edit = $this->dbca->stmt_query('SELECT * FROM goods_list_edit WHERE unitID = ?', 'i', $c_l);
                $goods_sale      = $this->dbca->stmt_query('SELECT * FROM goods_sale WHERE unitID = ?', 'i', $c_l);
                $goods_sale_edit = $this->dbca->stmt_query('SELECT * FROM goods_sale_edit WHERE unitID = ?', 'i', $c_l); 
                
                $goods_unit = new entity('goods_unit');
                $goods_unit->unitID = $c_l;
                if (!$this->dbca->fetch($goods_unit)) {
                	return array('code' => 400, 'message' => sprintf('单位号「%s」信息未找到，请核实'));
                }
                
                if ($goods_list || $goods_list_edit || $goods_sale || $goods_sale_edit) {
	            	return array('code' => 400, 'message' => sprintf('单位「%s」存在商品信息，不能删除',$goods_unit->unitName)); 
	            }
			}
        	
			//循环删除单位
            foreach( $delete_array as &$u_l ) {
                    
                //查询单位信息
                $unitInfo = new entity('goods_unit');
                $unitInfo->unitID = $u_l;
                if ($this->dbca->fetch( $unitInfo )) {
 
                	$this->dbca->delete( $unitInfo );
                	
                	//删除品牌标签
                	if($tagID_str == '' && $unitInfo->tagID != '')
                		$tagID_str .= $unitInfo->tagID ;
                		
                	else if($tagID_str != '' && $unitInfo->tagID != '')
                		$tagID_str .= '_' . $unitInfo->tagID ;
                }
                    
            }
            
            //删除单位标签
			$this->deleteTag(array('delete_str' => $tagID_str)) ;
            
            return array( 'code' => 200, 'message' => '商品单位删除成功' );
            
        } catch (Exception $e) {
            error_log($e->getMessage());
            if ($e->getCode() == 400) {
            	return array( 'code' => 400, 'message' => $e->getMessage() );
            } else {
            	return array( 'code' => 500, 'message' => '系统错误' );
            }
        }
	}
	
	/**
	 *单位的使用和禁用
	 *
	 * @param unknown_type $arg_array
	 * @return unknown
	 */
	public function actionUnit ( $arg_array ) {
		//参数检查
		if (!isset($arg_array['useFlg_str']) || $arg_array['useFlg_str'] == '')
            return array( 'code' => 400, 'message' => '缺少参数' );

        $str_array = explode('_', $arg_array['useFlg_str']);
        
        //查询单位是否存在或已经被操作
        $unitInfo = new entity('goods_unit');
        $unitInfo->unitID = $str_array[0] ;
        if (!$this->dbca->fetch( $unitInfo ))
        	return array( 'code' => 400, 'message' => sprintf('商品单位号「%d」信息未找到,请核实',$str_array[0]));
        	
        //检查单位状态是否已经被修改	
		if($unitInfo->useFlg == $str_array[1] && $str_array[1] == 1)
			return array( 'code' => 400, 'message' => sprintf('商品单位「%s」已启用',$unitInfo->unitName));
			
		if($unitInfo->useFlg == $str_array[1] && $str_array[1] == 0)
			return array( 'code' => 400, 'message' => sprintf('商品单位「%s」已禁用',$unitInfo->unitName));
			
		//保存和更新单位 	
     	$unitInfo->useFlg = $str_array[1] ; 
     	$this->dbca->save( $unitInfo , 'goods' );  
     	
		if($str_array[1] == 1)
            return array( 'code' => 200, 'message' => sprintf('商品单位「%s」启用成功',$unitInfo->unitName) );
            
		else if ($str_array[1] == 0)
			return array( 'code' => 200, 'message' => sprintf('商品单位「%s」禁用成功',$unitInfo->unitName) );
	}
	
	/**
	 * 保存和更新规格组
	 *
	 * @return unknown
	 */
	public function saveSpecGroupInfo ( $arg_array ) {
		//检查参数
		if (!isset($arg_array['specGroupName'] ,$arg_array['sortOrder'] ,$arg_array['creator'], $arg_array['specGroupID'], $arg_array['isColor']))
			return array( 'code' => 400, 'message' => '参数错误');
		
		$sortOrder 	 = $arg_array['sortOrder'] ;			//排序序号
		$specGroupID = $arg_array['specGroupID'] ;			//规格组号
		$isColor = $arg_array['isColor'];                   //是否为颜色规格属性
		$specGroupName = $arg_array['specGroupName'];       //规格组名字
		$useFlg = $arg_array['useFlg'];                     //启用状态
		$result = $this->dbca->stmt_query("SELECT * FROM goods_spec_group WHERE specGroupName = ?","s",$specGroupName);
		try{
			$specGroupInfo = new entity('goods_spec_group') ;
			//如果规格组号不为空则查询检查规格组号
			if($specGroupID != 0){
				//if( $specGroupID == 1 || $specGroupID == 2 )
					//throw new Exception('规格组「颜色,尺码」,不允许操作' , 400); 
					
				$specGroupInfo->specGroupID = $specGroupID ;
				if(!$this->dbca->fetch($specGroupInfo)){
					throw new Exception(sprintf('规格组号「%d」,的规格组不存在,请审核后再操作',$str_array[0]) , 400);
				}	
				//检查规格组排序有没有被使用	
				$issetSO = $this->dbca->stmt_query('SELECT COUNT(*) count FROM goods_spec_group WHERE sortOrder=? AND specGroupID!=?','ii' ,$sortOrder, $specGroupID) ;	
				if($issetSO[0]->count > 0)
					throw new Exception('排序序号已经被使用' , 400); 
						
				$specGroupInfo->editor = $arg_array['creator'] ;
			}else {
				//检查规格组排序有没有被使用	
				$issetSO = $this->dbca->stmt_query('SELECT COUNT(*) count FROM goods_spec_group WHERE sortOrder=?','i' ,$sortOrder) ;	
				if($issetSO[0]->count > 0){
					throw new Exception('排序序号已经被使用' , 400); 
				}
				if($result){
					throw new Exception('规格组名称已经存在,请审核后再操作',400);
				}	
				$specGroupInfo->creator = $arg_array['creator'] ;			
			}
			
			//保存和更新规格组信息
			$specGroupInfo->specGroupName = trim($arg_array['specGroupName']) ;
			$specGroupInfo->sortOrder 	  = $arg_array['sortOrder'] ;
			$specGroupInfo->isColor       = $arg_array['isColor'];
			$specGroupInfo->useFlg        = $arg_array['useFlg'];
			$this->dbca->save( $specGroupInfo , 'goods' ) ;
			return array( 'code' => 200, 'message' => '商品规格组保存成功' ) ;
		}catch (Exception $e) {
            if ($e->getCode() > 0) 
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }
        }
	}
	
	/**
	 * 删除规格组
	 *
	 */
	public function deleteSpecGroup ( $arg_array ) {
		
		//规格组号串检查
		if (!isset($arg_array['delete_str'])) {
            return array( 'code' => 400, 'message' => '缺少参数' );
		}    
            
		//将规格组号串截成数组
        $delete_array = explode('_', $arg_array['delete_str']);
        
        if (empty($delete_array)) {
            return array( 'code' => 400, 'message' => '请选择需要删除的商品规格' );
        }
        
        //检查当前规格是否存在商品
         foreach( $delete_array as &$c_l ) {
			$spec_group = new entity('goods_spec_group');
			$spec_group->specGroupID = $c_l;
			if (!$this->dbca->fetch($spec_group)) {
				return array('code' => 400, 'message' => sprintf('商品规格号「%d」信息未找到，请核实', $c_l));
			}
			
			//是否存在商品
			$group_relation = $this->dbca->stmt_query('SELECT * FROM goods_spec_relation WHERE specGroupID = ?','i',$c_l);	
			if ($group_relation) {
				return array('code' => 400, 'message' => sprintf('商品规格「%s」存在商品，不能删除', $spec_group->specGroupName));
			}
         }
        
        try {
        	$this->dbca->beginTransaction();
        	
			//循环删除规格组
            foreach( $delete_array as &$g_l ) {

                //查询规格组信息
                $sql_del_specgroup_info = 'DELETE FROM goods_spec_group WHERE specGroupID=?';
                
                $specgroup_del_result = $this->dbca->stmt_query($sql_del_specgroup_info,'i',$g_l);
                
				$sql_del_spec_info = 'DELETE FROM goods_spec WHERE specGroupID=?';
				
                $spec_del_result = $this->dbca->stmt_query($sql_del_spec_info,'i',$g_l);
            }
            
            $this->dbca->commit();
            
            return array( 'code' => 200, 'message' => '商品规格删除成功' );
        } catch (Exception $e) {
        	$this->dbca->rollBack();
        	error_log($e->getTraceAsString());
            if ($e->getCode() > 0) 
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }
        }
	}
	
	/**
	 * 商品规格组列表 
	 *
	 * @param unknown_type $arg_array 规格组参数
	 * @return unknown
	 */
	public function goodsSpecGroupList ( &$arg_array ) {
	
		 //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //规格组号
        if (isset($arg_array['specGroupID']) && is_numeric($arg_array['specGroupID'])) {
            $sql .= ' AND specGroupID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['specGroupID'];
        }

        //规格组名称
        if (isset($arg_array['specGroupName']) && !empty($arg_array['specGroupName'])) {
            $sql .= ' AND specGroupName LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . trim($arg_array['specGroupName']) . '%';
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM goods_spec_group ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM goods_spec_group ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
            	
				$specVal = '';
            	
        		$specArray = array(
        			'specGroupID' => $item->specGroupID,
        			'sortorder' => 'DESC',
        			'sortname' => 'sortOrder'
        		);
        		$specData = $this->goodsSpecList($specArray);
        		if ($specData) {
        			if (isset($arg_array['isSpec']) && $arg_array['isSpec'] == 1) {
	        			foreach ($specData as $key=>$spec){
	        				if (count($specData) == $key+1) {
	        					$specVal .= $spec['specName'];
	        				} else {
	        					$specVal .= $spec['specName'] . '，';
	        				}
	        			}
        			}
            		
            	}
            	
                $item_array[] = array(
                    'specGroupID' 	=> $item->specGroupID,
                    'specGroupName' => $item->specGroupName,
                    'sortOrder' 	=> $item->sortOrder,
                    'useFlg' 		=> $item->useFlg,
                    'isColor' 		=> $item->isColor,
                    'specVal'	    => $specVal,
                    'specArray'		=> $specData
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }
	}
	
	/**
	 * 商品规格列表 
	 *
	 * @param unknown_type $arg_array 规格组参数
	 * @return unknown
	 */
	public function goodsSpecList ( &$arg_array ) {
		//sql字符串
        $sql = '';
        
        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //规格名称
        if (isset($arg_array['specName']) && trim($arg_array['specName']) != '') {
            $sql .= ' AND sc.specName LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . trim($arg_array['specName']) . '%';
        }

        //规格ID
        if (isset($arg_array['specID']) && is_numeric($arg_array['specID'])) {
            $sql .= ' AND sc.specID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['specID'];
        }

        //规格组号
        if (isset($arg_array['specGroupID']) && trim($arg_array['specGroupID']) != '') {
            $sql .= ' AND sc.specGroupID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['specGroupID'];
        }
        
        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计促销行数
                $search_sql  = 'SELECT COUNT(*) AS count FROM goods_spec sc ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count  = $count_array[0]->count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY sc.%s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY sc.%s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询商品促销信息

            $search_sql = 'SELECT sc.specID,sc.specName,sc.specGroupID,sc.sortOrder,sc.useFlg,scg.specGroupName FROM goods_spec sc 
						   INNER JOIN goods_spec_group scg ON sc.specGroupID=scg.specGroupID' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            
            if ($temp_item_array) {
				foreach($temp_item_array as &$item) {
				    $item_array[] = array(
				        'specID' 	   => $item->specID,
				        'specName' 	   => $item->specName,
				        'specGroupID'  => $item->specGroupID,
				        'sortOrder'    => $item->sortOrder,
				        'useFlg' 	   => $item->useFlg
				    );
				}
            }
			
			return isset($item_array) ? $item_array : null;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }
	}
	
	/**
	 * 删除规格
	 *
	 */
	public function deleteSpec ( $arg_array ) {
		//规格号串检查
		if (!isset($arg_array['delete_str']))
            return array( 'code' => 400, 'message' => '缺少参数' );

        if (empty($arg_array['delete_str']))
            return array( 'code' => 400, 'message' => '请选择要删除的规格' );
            
		//将规格号串截成数组
        $delete_array = explode('_', $arg_array['delete_str']);

        try {
			//循环删除规格
            foreach( $delete_array as &$s_l ) {
                if (!is_numeric( $s_l ))
                    return array( 'code' => 400, 'message' => '参数错误' );
                    
	            //是否存在商品
				$group_relation = $this->dbca->stmt_query('SELECT * FROM goods_spec_relation WHERE specID = ?','i',$s_l);	
				if ($group_relation) {
					throw new Exception('当前规格存在商品，不能删除' , 400); 
				}     

                //查询规格信息
                $specInfo = new entity('goods_spec');
                $specInfo->SpecID = $s_l;
                if ($this->dbca->fetch( $specInfo ))
                    $this->dbca->delete( $specInfo );
            }
            return array( 'code' => 200, 'message' => '删除成功' );
        } catch (Exception $e) {
            error_log($e->getMessage());
            if ($e->getCode() == 400) {
            	return array( 'code' => 500, 'message' => $e->getMessage() );
            } else {
            	return array( 'code' => 500, 'message' => '系统错误' );
            }	
        }
	}
	
	/**
	 * 规格的使用和禁用
	 *
	 * @param unknown_type $arg_array
	 * @return unknown
	 */
	public function statusGoodsSpec ( $arg_array ) {
		//检查参数
		if (!isset($arg_array['useFlg_str']) || $arg_array['useFlg_str'] == '')
            return array( 'code' => 400, 'message' => '缺少参数' );

        $str_array = explode('_', $arg_array['useFlg_str']);
        
        //查询规格是否存在或已经被操作
        $specInfo = new entity('goods_spec');
        $specInfo->specID = $str_array[0] ;
        if (!$this->dbca->fetch( $specInfo ))
        	return array( 'code' => 400, 'message' => sprintf('商品规格号「%d」信息未找到，请核实',$str_array[0]));
        	
        //检查规格状态是否已经修改
		if($specInfo->useFlg == $str_array[1] && $str_array[1] == 1)
			return array( 'code' => 400, 'message' => sprintf('商品规格「%s」已启用',$specInfo->specName));
			
		if($specInfo->useFlg == $str_array[1] && $str_array[1] == 0)
			return array( 'code' => 400, 'message' => sprintf('商品规格「%s」已禁用',$specInfo->specName));
			
		//修改规格状态	
     	$specInfo->useFlg = $str_array[1] ; 
     	$this->dbca->save( $specInfo , 'goods' );  
     	
		if($str_array[1] == 1)
            return array( 'code' => 200, 'message' => sprintf('商品规格「%s」启用成功',$specInfo->specName) );
            
		else if ($str_array[1] == 0)
			return array( 'code' => 200, 'message' => sprintf('商品规格「%s」禁用成功',$specInfo->specName) );
	}
	
	/**
	 * 保存和更新规格
	 *
	 * @return unknown
	 */
	public function saveGoodsSpec ( $arg_array ) {

		//检查参数
		if (!isset($arg_array['specID'], $arg_array['specName'], $arg_array['sortOrder'], $arg_array['isColor'], $arg_array['spec_array'])) {
			return array('code' => 400, 'message' => '缺少参数');
		}
		
		//检查规格名称是否重复
		$check_spec_group = new entity('goods_spec_group');
		$check_spec_group->specGroupName = $arg_array['specName'];
		if ($this->dbca->fetch($check_spec_group)) {
			if (!empty($arg_array['specID'])) {
				if ($check_spec_group->specGroupID != $arg_array['specID']) {
					return array('code' => 400, 'message' => sprintf('商品规格「%s」已经存在', $arg_array['specName']));
				}
			} else {
				return array('code' => 400, 'message' => sprintf('商品规格「%s」已经存在', $arg_array['specName']));
			}
		}
		
		//检查排序序号是否重复
		$sort_spec_group = new entity('goods_spec_group');
		$sort_spec_group->sortOrder = $arg_array['sortOrder'];
		if ($this->dbca->fetch($sort_spec_group)) {
			if (!empty($arg_array['specID'])) {
				if ($sort_spec_group->specGroupID != $arg_array['specID']) {
					return array('code' => 400, 'message' => sprintf('商品排序序号「%d」已经存在', $arg_array['sortOrder']));
				}
			} else {
				return array('code' => 400, 'message' => sprintf('商品排序序号「%d」已经存在', $arg_array['sortOrder']));
			}
		}
		
		$goods_spec_group = new entity('goods_spec_group');
		if (!empty($arg_array['specID'])) {
			$goods_spec_group->specGroupID = $arg_array['specID'];
			if (!$this->dbca->fetch($goods_spec_group)) {
				return array('code' => 400, 'message' => '商品规格信息不存在');
			}	
			
			$goods_spec_group->editor = $arg_array['creator'];
			
			//删除旧的规格值，并判断是否存在商品
			$check_spec = $this->dbca->stmt_query('SELECT * FROM goods_spec_relation WHERE specGroupID = ?', 'i', $arg_array['specID']);
			if ($check_spec) {
				return array('code' => 400, 'message' => '当前商品规格存在商品信息，不能操作');
			}
			
			$this->dbca->stmt_query('DELETE FROM goods_spec WHERE specGroupID = ?', 'i', $arg_array['specID']);
			
		} else {
			$goods_spec_group->creator = $arg_array['creator'];
		}
		$goods_spec_group->specGroupName = $arg_array['specName'];
		$goods_spec_group->sortOrder     = $arg_array['sortOrder'];
		$goods_spec_group->useFlg        = 1;
		$goods_spec_group->isColor       = $arg_array['isColor'];
		
		$this->dbca->beginTransaction();
		try{
			$this->dbca->save($goods_spec_group);
			
			//获取规格ID
			if (!empty($arg_array['specID'])) {
				$specGroupID = $arg_array['specID'];
			} else {
				$specGroup = $this->dbca->stmt_query('SELECT MAX(specGroupID) max_id FROM goods_spec_group');
				$specGroupID = $specGroup[0]->max_id;
			}
			
			if (!empty($arg_array['spec_array'])) {
				$arg_array['spec_array'] = array_unique($arg_array['spec_array']);
				
				$arg_array['spec_array'] = array_reverse($arg_array['spec_array']);

				foreach ($arg_array['spec_array'] as $s_l) {
					//获取规格值最大排序
					$max_sort = $this->dbca->stmt_query('SELECT MAX(sortOrder)+1 max_sort FROM goods_spec');
					if (empty($max_sort[0]->max_sort)) {
						$max_sort = 1;
					} else {
						$max_sort = $max_sort[0]->max_sort;
					}
					
					$goods_spec = new entity('goods_spec');
					$goods_spec->creator     = $arg_array['creator'];
					$goods_spec->specName    = $s_l;
					$goods_spec->specGroupID = $specGroupID;
					$goods_spec->sortOrder   = $max_sort;
					$goods_spec->useFlg      = 1;
					
					$this->dbca->save($goods_spec);
				}
			}
			
			$this->dbca->commit();
			if (!empty($arg_array['specID'])) {
				return array('code' => 200, 'message' => '商品规格更新成功', 'specID' => $arg_array['specID'], 'sortOrder' => $arg_array['sortOrder']+1);
			} else {
				return array('code' => 200, 'message' => '商品规格保存成功', 'specID' => '', 'sortOrder' => $arg_array['sortOrder']+1);
			}
		
		}catch(Exception $e){
			$this->dbca->rollBack();
			
			return array('code' => 400, 'message' => '商品规格保存失败');
		}
	}
	
	/**
	 * 标签组的使用和禁用
	 *
	 * @param unknown_type $arg_array
	 * @return unknown
	 */
	public function statusTagGroup ( $arg_array ) {
		//检查参数
		if (!isset($arg_array['useFlg_str']) || $arg_array['useFlg_str'] == '')
            return array( 'code' => 400, 'message' => '缺少参数' );

        $str_array = explode('_', $arg_array['useFlg_str']);
        
        //查询标签组是否存在或已经被操作
        $tagGroupInfo = new entity('goods_tag_group');
        $tagGroupInfo->tagGroupID = $str_array[0] ;
        if (!$this->dbca->fetch( $tagGroupInfo ))
        	return array( 'code' => 400, 'message' => sprintf('商品标签组号「%d」信息未找到，请核实',$str_array[0]));
        	
        //检查标签组状态是否已经修改
		if($tagGroupInfo->useFlg == $str_array[1] && $str_array[1] == 1)
			return array( 'code' => 400, 'message' => sprintf('商品标签组「%s」已启用',$tagGroupInfo->tagGroupName));
			
		if($tagGroupInfo->useFlg == $str_array[1] && $str_array[1] == 0)
			return array( 'code' => 400, 'message' => sprintf('商品标签组「%s」已禁用',$tagGroupInfo->tagGroupName));
			
		//修改标签组状态	
     	$tagGroupInfo->useFlg = $str_array[1] ; 
     	$this->dbca->save( $tagGroupInfo , 'goods' );  
     	
		if($str_array[1] == 1)
            return array( 'code' => 200, 'message' => sprintf('商品标签组「%s」启用成功',$tagGroupInfo->tagGroupName) );
            
		else if ($str_array[1] == 0)
			return array( 'code' => 200, 'message' => sprintf('商品标签组「%s」禁用成功',$tagGroupInfo->tagGroupName) );
	}

	/**
	 * 删除标签组
	 *
	 * @param unknown_type $arg_array
	 * @return unknown
	 */
	public function deleteTagGroup ( $arg_array ) {
		//标签组号串检查
		if (!isset($arg_array['delete_str']))
            return array( 'code' => 400, 'message' => '缺少参数' );

        if (empty($arg_array['delete_str']))
            return array( 'code' => 400, 'message' => '请选择要删除的标签组' );
            
		//将标签组号串截成数组
        $delete_array = explode('_', $arg_array['delete_str']);

        try {
			//循环删除标签组
            foreach( $delete_array as &$t_g ) {
                if (!is_numeric( $t_g ))
                    return array( 'code' => 400, 'message' => '参数错误' );

                //查询标签组信息
                $tagGroupInfo = new entity('goods_tag_group');
                $tagGroupInfo->tagGroupID = $t_g;
                if ($this->dbca->fetch( $tagGroupInfo )) {
                    $this->dbca->delete( $tagGroupInfo );
                }    
                
                $this->dbca->stmt_query('DELETE FROM goods_tag WHERE tagGroupID = ?', 'i', $t_g);
            }
            return array( 'code' => 200, 'message' => '商品标签组删除成功' );
        } catch (Exception $e) {
            error_log($e->getMessage());
            return array( 'code' => 500, 'message' => '系统错误' );
        }
	}
	
	
	/**
	 * 保存和更新标签组
	 *
	 * @return unknown
	 */
	public function saveTagGroup ( $arg_array ) {
		//检查参数
		if (!isset($arg_array['creator'] ,$arg_array['tagGroupID'] ,$arg_array['tagGroupName'], $arg_array['memoName'] , $arg_array['sortOrder'] , $arg_array['useFlg'] ))
			return array( 'code' => 400, 'message' => '参数错误');
		
		$creator	  = $arg_array['creator'] ;				//创建或者修改者
		$tagGroupID   = $arg_array['tagGroupID'] ;			//标签组号
		$tagGroupName = trim($arg_array['tagGroupName']) ;	//标签组名称 
		$memoName	  = trim($arg_array['memoName']) ;		//后台名称
		$sortOrder	  = trim($arg_array['sortOrder']) ;		//排序序号
		$useFlg		  = $arg_array['useFlg'] ;				//使用标志
		
		try{
			
			$tagGroupInfo = new entity('goods_tag_group') ;
			
			//如果标签组号不为空则查询检查标签组号
			if($tagGroupID != 0){
					
				$tagGroupInfo->tagGroupID = $tagGroupID ;
				if(!$this->dbca->fetch($tagGroupInfo))
					throw new Exception(sprintf('标签组号「%d」,的标签组不存在,请审核后再操作',$str_array[0]) , 400); 
					
				//检查标签组排序有没有被使用	
				$issetSO = $this->dbca->stmt_query('SELECT COUNT(*) count FROM goods_tag_group WHERE sortOrder=? AND tagGroupID!=?','ii' ,$sortOrder, $tagGroupID) ;	
				if($issetSO[0]->count > 0)
					throw new Exception('排序序号已经被使用' , 400); 
						
				$tagGroupInfo->editor = $creator ;
			}else {
				//检查标签组排序有没有被使用	
				$issetSO = $this->dbca->stmt_query('SELECT COUNT(*) count FROM goods_tag_group WHERE sortOrder=?','i' ,$sortOrder) ;	
				if($issetSO[0]->count > 0)
					throw new Exception('排序序号已经被使用' , 400); 
					
				$tagGroupInfo->creator = $creator ;			
			}
			
			//保存和更新标签组信息
			$tagGroupInfo->tagGroupName = $tagGroupName;
			$tagGroupInfo->memoName 	= $memoName ;
			$tagGroupInfo->sortOrder 	= $sortOrder ;
			$tagGroupInfo->useFlg 		= $useFlg;
			$this->dbca->save( $tagGroupInfo , 'goods' ) ;
			
			return array( 'code' => 200, 'message' => '商品标签组保存成功' ) ;
			
		}catch (Exception $e) {
            if ($e->getCode() > 0) 
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }
        }
	}
	
	/**
	 * 标签列表 
	 *
	 * @param unknown_type $arg_array 标签参数
	 * @return unknown
	 */
	public function goodsTagList ( &$arg_array ) {
		//sql字符串
        $sql = '';
        
        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //标签名称
        if (isset($arg_array['tagName']) && trim($arg_array['tagName']) != '') {
            $sql .= ' AND t.tagName LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . trim($arg_array['tagName']) . '%';
        }

        //标签ID
        if (isset($arg_array['tagID']) && trim($arg_array['tagID']) != '') {
            $sql .= ' AND t.tagID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['tagID'];
        }

        //标签组号
        if (isset($arg_array['tagGroupID']) && trim($arg_array['tagGroupID']) != '') {
            $sql .= ' AND t.tagGroupID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['tagGroupID'];
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计促销行数
                $search_sql  = 'SELECT COUNT(*) AS count FROM goods_tag t WHERE 1=1 ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count  = $count_array[0]->count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY t.%s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY t.%s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询商品促销信息
            $search_sql = 'SELECT t.tagID,t.tagName, t.tagGroupID,gt.tagGroupName,t.sortOrder,t.useFlg FROM goods_tag t  INNER JOIN goods_tag_group gt ON t.tagGroupID=gt.tagGroupID WHERE 1=1 ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;
            
            return $temp_item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }
	}
	
	/**
	 * 标签的使用和禁用
	 *
	 * @param unknown_type $arg_array
	 * @return unknown
	 */
	public function statusGoodsTag ( $arg_array ) {
		//检查参数
		if (!isset($arg_array['useFlg_str']) || $arg_array['useFlg_str'] == '')
            return array( 'code' => 400, 'message' => '缺少参数' );

        $str_array = explode('_', $arg_array['useFlg_str']);
        
        //标签是否存在或已经被操作
        $tagInfo = new entity('goods_tag');
        $tagInfo->tagID = $str_array[0] ;
        if (!$this->dbca->fetch( $tagInfo ))
        	return array( 'code' => 400, 'message' => sprintf('标签号「%d」信息未找到，请核实',$str_array[0]));
        	
        //标签状态是否已经修改
		if($tagInfo->useFlg == $str_array[1] && $str_array[1] == 1)
			return array( 'code' => 400, 'message' => sprintf('商品标签「%s」已启用',$tagInfo->tagName));
			
		if($tagInfo->useFlg == $str_array[1] && $str_array[1] == 0)
			return array( 'code' => 400, 'message' => sprintf('商品标签「%s」禁用',$tagInfo->tagName));
			
		//修改标签状态	
     	$tagInfo->useFlg = $str_array[1] ; 
     	$this->dbca->save( $tagInfo , 'goods' );  
     	
		if($str_array[1] == 1)
            return array( 'code' => 200, 'message' => sprintf('商品标签「%s」启用成功',$tagInfo->tagName) );
            
		else if ($str_array[1] == 0)
			return array( 'code' => 200, 'message' => sprintf('商品标签「%s」禁用成功',$tagInfo->tagName) );
	}
	
	
	/**
	 * 删除标签
	 *
	 * @param unknown_type $arg_array
	 * @return unknown
	 */
	public function deleteTag ( $arg_array ) {
		//标签号串检查
		if (!isset($arg_array['delete_str']))
            return array( 'code' => 400, 'message' => '缺少参数' );

        if (empty($arg_array['delete_str']))
            return array( 'code' => 400, 'message' => '请选择要删除的标签组' );
            
		//将标签号串截成数组
        $delete_array = explode('_', $arg_array['delete_str']);

        try {
			//循环删除标签
            foreach( $delete_array as &$t_g ) {
                if (!is_numeric( $t_g ))
                    return array( 'code' => 400, 'message' => '参数错误' );

                //查询标签信息
                $tagGroupInfo = new entity('goods_tag');
                $tagGroupInfo->tagID = $t_g;
                if ($this->dbca->fetch( $tagGroupInfo ))
                    $this->dbca->delete( $tagGroupInfo );
            }
            return array( 'code' => 200, 'message' => '删除成功' );
        } catch (Exception $e) {
            error_log($e->getMessage());
            return array( 'code' => 500, 'message' => '系统错误' );
        }
	}
	
	/**
	 * 保存和更新标签
	 *
	 * @return unknown
	 */
	public function saveTagInfo ( $arg_array ) {
		//检查参数
		if (!isset($arg_array['creator'] ,$arg_array['tagID'] ,$arg_array['tagName'], $arg_array['tagGroupID'] ,$arg_array['sortOrder'] ,$arg_array['useFlg'] ))
			return array( 'code' => 400, 'message' => '参数错误');
		
		$creator 	 = $arg_array['creator'] ;			//创建者或修改者
		$tagID 		 = $arg_array['tagID'] ;			//标签号
		$tagName 	 = trim($arg_array['tagName']) ;	//标签名称
		$tagGroupID  = $arg_array['tagGroupID'] ;		//标签组号
		$sortOrder   = trim($arg_array['sortOrder']) ;	//排列序号
		$useFlg	     = $arg_array['useFlg'] ;			//使用标志
		try{
			$tagInfo = new entity('goods_tag') ;
			//如果标签组号不为空则查询检查标签组号
			if($tagID != 0){
				$tagInfo->tagID = $tagID ;
				if(!$this->dbca->fetch($tagInfo))
					throw new Exception(sprintf('标签号「%d」,的标签不存在,请审核后再操作',$str_array[0]) , 400); 
					
				//检查标签组排序有没有被使用	
				$issetSO = $this->dbca->stmt_query('SELECT COUNT(*) count FROM goods_tag WHERE sortOrder=? AND tagID!=?','ii' ,$sortOrder, $tagID) ;	
				if($issetSO[0]->count > 0)
					throw new Exception('排序序号已经被使用' , 400); 
						
				$tagInfo->editor = $arg_array['creator'] ;
			}else {
				//检查标签组排序有没有被使用	
				$issetSO = $this->dbca->stmt_query('SELECT COUNT(*) count FROM goods_tag WHERE sortOrder=?','i' ,$sortOrder) ;	
				if($issetSO[0]->count > 0)
					throw new Exception('排序序号已经被使用' , 400); 
					
				$tagInfo->creator = $arg_array['creator'] ;			
			}
			
			//保存和更新标签组信息
			$tagInfo->tagName    = $tagName ;
			$tagInfo->sortOrder  = $sortOrder ;
			$tagInfo->tagGroupID = $tagGroupID ;
			$tagInfo->useFlg	 = $useFlg ;
			$this->dbca->save( $tagInfo , 'goods' ) ;
			
			return array( 'code' => 200, 'message' => '商品标签保存成功' ) ;
			
		}catch (Exception $e) {
            if ($e->getCode() > 0) 
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }
        }
	}
	
	/**
	 *  保存商品属性对应标签
	 *
	 * @param unknown_type $arg_array = array('tagName'=> '标签名称' ,'tagID'=>10 , 'tagGroupID' => 1 , 'creator' => 'system') 
	 */
	public function commPropertyTag ( $arg_array ) {
		//参数查检
		if(!isset($arg_array['tagID'] , $arg_array['tagName'] , $arg_array['tagGroupID'] ,$arg_array['creator'] ))
			return array( 'code' => 400, 'message' => '参数错误');
			
		//参数对应
		$tagID 	 	= $arg_array['tagID'] ;				//商品标签号
		$tagName 	= $arg_array['tagName'] ;			//商品标签名称
		$tagGroupID = $arg_array['tagGroupID'] ;		//商品标签组号
		$creator 	= $arg_array['creator'] ; 			//标签创建和修改者
		
		try{
			//判断商品是新增还是更新
			if($tagID == 0){
				//得到最大的标签排序
				$getSortOrder = $this->dbca->stmt_query('SELECT IF(MAX(sortOrder) IS NULL ,1 , MAX(sortOrder)+1) AS max_sortOrder FROM goods_tag') ;
				$maxSortOrder = $getSortOrder[0]->max_sortOrder ; 
				
				//判断标签是否已经存在
				$issetTagInfo = new entity('goods_tag') ;
				$issetTagInfo->tagGroupID = $tagGroupID ;
				$issetTagInfo->tagName	  = $tagName ;
				if($this->dbca->fetch($issetTagInfo))
					throw new Exception(sprintf('标签「%s」在标签组号「%d」的标签组中，已经存在 ' ,$tagName, $tagGroupID) , 400); 
				
				$issetTagInfo->sortOrder = $maxSortOrder ;
				$issetTagInfo->useFlg 	 = 1 ;
				$issetTagInfo->creator 	 = $creator ;
				$this->dbca->save($issetTagInfo , 'goods') ;
				$tagID = $this->dbca->insert_id ; 
				return array( 'code' =>200 , 'message' => $tagID ); 
			}else{
				//检查商品标签是否存在
				$issetTagInfo = new entity('goods_tag') ;
				$issetTagInfo->tagGroupID = $tagGroupID ;
				$issetTagInfo->tagID	  = $tagID ;
				if(!$this->dbca->fetch($issetTagInfo)){
				//得到最大的标签排序
				$getSortOrder = $this->dbca->stmt_query('SELECT IF(MAX(sortOrder) IS NULL ,1 , MAX(sortOrder)+1) AS max_sortOrder FROM goods_tag') ;
				$maxSortOrder = $getSortOrder[0]->max_sortOrder ;
                    $issetTagInfo->sortOrder = $maxSortOrder ;
                    $issetTagInfo->useFlg 	 = 1 ;
                    //throw new Exception(sprintf('标签组号「%d」的标签组中，不存在标签「%s」' , $tagGroupID ,$tagName ) , 400);
                }
				$issetTagInfo->tagName = $tagName ;
				$issetTagInfo->editor  = $creator ;
				$this->dbca->save($issetTagInfo , 'goods') ;
				return array( 'code' =>200 , 'message' => $tagID ); 
			}
		}catch (Exception $e) {
			 if ($e->getCode() > 0) 
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }
		}
	}
	
	/**
	 * 商品公用分类下拉菜单
	 *
	 */
	public function goodsCategoryList () {
		$categoryArray = array () ;
		//大分类号
		$bcData = $this->dbca->stmt_query ('SELECT bigCategoryID ,description  ,sortOrder FROM goods_bigcategory WHERE useFlg=1 ORDER BY sortOrder,bigCategoryID ') ;
		//中分类号
		$mcData = $this->dbca->stmt_query ('SELECT bigCategoryID,midCategoryID ,description ,useFlg ,sortOrder FROM goods_midcategory WHERE useFlg=1  ORDER BY sortOrder,midCategoryID') ;
		//小分类号
		$scData = $this->dbca->stmt_query ('SELECT bigCategoryID,midCategoryID,smallCategoryID ,description  ,sortOrder FROM goods_smallcategory WHERE useFlg=1 ORDER BY sortOrder,smallCategoryID') ;
		
		$categoryArray ['bc'] = $bcData ;
		$categoryArray ['mc'] = $mcData ;
		$categoryArray ['sc'] = $scData ;
		
		return $categoryArray ;
	}
	
	/**
	 * 销售商品列表
	 *
	 * @param unknown_type $arg_array
	 */
	public function searchGoodsList ( &$arg_array ) {
		//sql字符串
        $sql = '';
        
        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();
        
        //商品列表数组
        $list_array = array();
        
        //网购号
        if (isset($arg_array['postID']) && is_numeric($arg_array['postID'])) {
        	$sql .= ' AND postID = ?';
            $params_type .= 'i';
            $params_array[] = trim($arg_array['postID']) ;
        }
        
        //商品编码
        if (isset($arg_array['product_code']) && trim($arg_array['product_code']) != '') {
            $sql .= ' AND product_code = ?';
            $params_type .= 's';
            $params_array[] = trim($arg_array['product_code']) ;
        }
        
		//商品大分类
        if (isset($arg_array['bigCate']) && $arg_array['bigCate'] != 0) {
            $sql .= ' AND bigCategoryID = ?';
            $params_type .= 'i';
            $params_array[] = trim($arg_array['bigCate']) ;
        }
        
        //商品中分类
        if (isset($arg_array['midCate']) && $arg_array['midCate'] != 0) {
            $sql .= ' AND midCategoryID = ?';
            $params_type .= 'i';
            $params_array[] = trim($arg_array['midCate']) ;
        }
        
         //商品小分类
        if (isset($arg_array['smallCate']) && $arg_array['smallCate'] != 0) {
            $sql .= ' AND smallCategoryID = ?';
            $params_type .= 'i';
            $params_array[] = trim($arg_array['smallCate']) ;
        }
        
        //商品名称
        if (isset($arg_array['goodsName']) && trim($arg_array['goodsName']) != '') {
            $sql .= ' AND goodsName LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . trim($arg_array['goodsName']) . '%';
        }

        //商品开始价格
        if (isset($arg_array['startPrice']) && trim($arg_array['startPrice']) != '') {
            $sql .= ' AND salePrice >= ?';
            $params_type .= 'd';
            $params_array[] = trim($arg_array['startPrice']) ;
        }
        
        //商品结束价格
        if (isset($arg_array['endPrice']) && trim($arg_array['endPrice']) != '') {
            $sql .= ' AND salePrice <= ?';
            $params_type .= 'd';
            $params_array[] = trim($arg_array['endPrice']) ;
        }
        
        /*
        //商品上下架
        if (isset($arg_array['forsale']) && $arg_array['forsale'] != 0) {
            $sql .= ' AND forsale = ?';
            $params_type .= 'i';

            if($arg_array['forsale'] == 1)
            	$params_array[] = 1 ;
            elseif($arg_array['forsale'] == 2)
            	$params_array[] = 0 ;
        }
		*/
        $sql .= ' AND forsale=1';
       
        
        //库存标志
        if (isset($arg_array['useFlg']) && $arg_array['useFlg'] != 0) {
            $sql .= ' AND useFlg = ?';
            $params_type .= 'i';
            $params_array[] = trim($arg_array['useFlg']) ;
        }
        
        //品牌
        if (isset($arg_array['brandID']) && $arg_array['brandID'] != 0) {
            $sql .= ' AND brandID = ?';
            $params_type .= 'i';
            $params_array[] = trim($arg_array['brandID']) ;
        }
        
        if (isset($arg_array['extendSql']) && !empty($arg_array['extendSql'])) {
        	$sql .= $arg_array['extendSql'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计促销行数
                $search_sql  = 'SELECT COUNT(*) count FROM goods_list ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count  = $count_array[0]->count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询商品促销信息
            $search_sql = 'SELECT * FROM goods_list ' . $sql;

            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;
                
            $goodsHandler = new goodsHandler();
			
            foreach($temp_item_array as &$item) {
                $list_array[] = array(
                	'uid' => $item->uid,
                    'goodsID' => $item->goodsID,
                    'goodsName' => $item->goodsName,
                    'postID' => $item->postID,
                    'bigCategoryID' => $item->bigCategoryID,
                    'bigCategoryName' => $item->bigCategoryName,
                    'midCategoryID' => $item->midCategoryID,
                    'midCategoryName' => $item->midCategoryName,
                    'smallCategoryID' => $item->smallCategoryID,
                    'smallCategoryName' => $item->smallCategoryName,
                    'forsale' => $item->forsale,
                    'spec' => $item->spec,
                    'useFlg' => $item->useFlg,
                    'marketPrice' => $item->marketPrice,
                    'salePrice' => $item->salePrice,
                    'pointPrice' => $item->pointPrice,
                    'addPoints' => $item->addPoints,
                    'salePoints' => $item->salePoints,
                    'discountFlg' => $item->discountFlg,
                    'pointsByFlg' => $item->pointsByFlg,
                    'forsale' => $item->forsale,
                    'brandID' => $item->brandID,
                    'brandName' => $item->brandName,
                    'unitID' => $item->unitID,
                    'unitName' => $item->unitName,
                    'brief' => $item->brief,
                    'description' => $item->description,
                    'goodsMainPic' => $this->setImgLink($item->goodsMainPic),
                    'img_link' => $this->setImgLink($item->goodsMainPic),
                    'memo' => $item->memo,
                    'goodsLength' => $item->goodsLength,
                    'goodsWidth' => $item->goodsWidth,
                    'goodsHeight' => $item->goodsHeight,
                    'goodsWeight' => $item->goodsWeight,
                    'barcode' => $item->barcode,
                    'product_code' => $item->product_code,
                    'twoPostID' => $item->twoPostID,
                    'product_mainID' => $item->product_mainID,
                    'site_id' => $item->site_id,
                    'shelfLife' => $item->shelfLife,
                    'saletotal' => $item->saletotal,
                    'link' => $this->setLink( $item->uid ),
                    'wap_link' => $this->setLink( $item->uid, 'wap' ),
                    'bigCategoryLink' => $this->setCategoryLink($item->bigCategoryID),
                    'midCategoryLink' => $this->setCategoryLink($item->bigCategoryID, $item->midCategoryID),
                    'smallCategoryLink' => $this->setCategoryLink($item->bigCategoryID, $item->midCategoryID, $item->smallCategoryID),
                );
            }
            
            return $list_array;
			
        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }
	}
	
	/**
	 * 根据分类查找商品
	 *
	 * @param unknown_type $arg_array
	 */
	public function searchGoodsListByCate ( &$arg_array ) {
		//sql字符串
        $sql = '';
        
        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();
        
        //商品列表数组
        $list_array = array();
        
        //网购号
        if (isset($arg_array['postID']) && is_numeric($arg_array['postID'])) {
        	$sql .= ' AND gl.postID = ?';
            $params_type .= 'i';
            $params_array[] = trim($arg_array['postID']) ;
        }
        
        //商品编码
        if (isset($arg_array['product_code']) && trim($arg_array['product_code']) != '') {
            $sql .= ' AND gl.product_code = ?';
            $params_type .= 's';
            $params_array[] = trim($arg_array['product_code']) ;
        }
        
		//商品大分类
        if (isset($arg_array['bigCate']) && $arg_array['bigCate'] != 0) {
            $sql .= ' AND gcr.bigCategoryID = ?';
            $params_type .= 'i';
            $params_array[] = trim($arg_array['bigCate']) ;
        }
        
        //商品中分类
        if (isset($arg_array['midCate']) && $arg_array['midCate'] != 0) {
            $sql .= ' AND gcr.midCategoryID = ?';
            $params_type .= 'i';
            $params_array[] = trim($arg_array['midCate']) ;
        }
        
         //商品小分类
        if (isset($arg_array['smallCate']) && $arg_array['smallCate'] != 0) {
            $sql .= ' AND gcr.smallCategoryID = ?';
            $params_type .= 'i';
            $params_array[] = trim($arg_array['smallCate']) ;
        }
        
        //商品名称
        if (isset($arg_array['goodsName']) && trim($arg_array['goodsName']) != '') {
            $sql .= ' AND goodsName LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . trim($arg_array['goodsName']) . '%';
        }

        //商品开始价格
        if (isset($arg_array['startPrice']) && trim($arg_array['startPrice']) != '') {
            $sql .= ' AND salePrice >= ?';
            $params_type .= 'd';
            $params_array[] = trim($arg_array['startPrice']) ;
        }
        
        //商品结束价格
        if (isset($arg_array['endPrice']) && trim($arg_array['endPrice']) != '') {
            $sql .= ' AND salePrice <= ?';
            $params_type .= 'd';
            $params_array[] = trim($arg_array['endPrice']) ;
        }
        
        /*
        //商品上下架
        if (isset($arg_array['forsale']) && $arg_array['forsale'] != 0) {
            $sql .= ' AND forsale = ?';
            $params_type .= 'i';

            if($arg_array['forsale'] == 1)
            	$params_array[] = 1 ;
            elseif($arg_array['forsale'] == 2)
            	$params_array[] = 0 ;
        }
		*/
        $sql .= ' AND forsale=1';
       
        
        //库存标志
        if (isset($arg_array['useFlg']) && $arg_array['useFlg'] != 0) {
            $sql .= ' AND useFlg = ?';
            $params_type .= 'i';
            $params_array[] = trim($arg_array['useFlg']) ;
        }
        
        //品牌
        if (isset($arg_array['brandID']) && $arg_array['brandID'] != 0) {
            $sql .= ' AND brandID = ?';
            $params_type .= 'i';
            $params_array[] = trim($arg_array['brandID']) ;
        }
        
        if (isset($arg_array['extendSql']) && !empty($arg_array['extendSql'])) {
        	$sql .= $arg_array['extendSql'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计促销行数
                $search_sql  = 'SELECT COUNT(*) count FROM goods_list gl
                					JOIN goods_category_relation gcr ON gl.postID = gcr.postID	 
                				' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count  = $count_array[0]->count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询商品促销信息
            $search_sql = 'SELECT gl.* FROM goods_list gl JOIN goods_category_relation gcr ON gl.postID = gcr.postID ' . $sql;

            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;
                
            $goodsHandler = new goodsHandler();
			
            foreach($temp_item_array as &$item) {
                $list_array[] = array(
                	'uid' => $item->uid,
                    'goodsID' => $item->goodsID,
                    'goodsName' => $item->goodsName,
                    'postID' => $item->postID,
                    'bigCategoryID' => $item->bigCategoryID,
                    'bigCategoryName' => $item->bigCategoryName,
                    'midCategoryID' => $item->midCategoryID,
                    'midCategoryName' => $item->midCategoryName,
                    'smallCategoryID' => $item->smallCategoryID,
                    'smallCategoryName' => $item->smallCategoryName,
                    'forsale' => $item->forsale,
                    'spec' => $item->spec,
                    'useFlg' => $item->useFlg,
                    'marketPrice' => $item->marketPrice,
                    'salePrice' => $item->salePrice,
                    'pointPrice' => $item->pointPrice,
                    'addPoints' => $item->addPoints,
                    'salePoints' => $item->salePoints,
                    'discountFlg' => $item->discountFlg,
                    'pointsByFlg' => $item->pointsByFlg,
                    'forsale' => $item->forsale,
                    'brandID' => $item->brandID,
                    'brandName' => $item->brandName,
                    'unitID' => $item->unitID,
                    'unitName' => $item->unitName,
                    'brief' => $item->brief,
                    'description' => $item->description,
                    'goodsMainPic' => $this->setImgLink($item->goodsMainPic),
                    'img_link' => $this->setImgLink($item->goodsMainPic),
                    'memo' => $item->memo,
                    'goodsLength' => $item->goodsLength,
                    'goodsWidth' => $item->goodsWidth,
                    'goodsHeight' => $item->goodsHeight,
                    'goodsWeight' => $item->goodsWeight,
                    'barcode' => $item->barcode,
                    'product_code' => $item->product_code,
                    'twoPostID' => $item->twoPostID,
                    'product_mainID' => $item->product_mainID,
                    'site_id' => $item->site_id,
                    'shelfLife' => $item->shelfLife,
                    'saletotal' => $item->saletotal,
                    'link' => $this->setLink( $item->uid ),
                    'wap_link' => $this->setLink( $item->uid, 'wap' ),
                    'bigCategoryLink' => $this->setCategoryLink($item->bigCategoryID),
                    'midCategoryLink' => $this->setCategoryLink($item->bigCategoryID, $item->midCategoryID),
                    'smallCategoryLink' => $this->setCategoryLink($item->bigCategoryID, $item->midCategoryID, $item->smallCategoryID),
                );
            }
            
            return $list_array;
			
        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }
	}

    /**
     * 待发布商品列表
     *
     * @param unknown_type $arg_array
     */
    public function getGoodsListEdit ( &$arg_array ) {
        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();


        //商品编码
        if (isset($arg_array['product_code']) && trim($arg_array['product_code']) != '') {
            $sql .= ' AND product_code = ?';
            $params_type .= 's';
            $params_array[] = trim($arg_array['product_code']) ;
        }
        
        if (isset($arg_array['postID']) && trim($arg_array['postID']) != '') {
            $sql .= ' AND postID = ?';
            $params_type .= 'i';
            $params_array[] = trim($arg_array['postID']) ;
        }

        //商品大分类
        if (isset($arg_array['bigCate']) && $arg_array['bigCate'] != 0) {
            $sql .= ' AND bigCategoryID = ?';
            $params_type .= 'i';
            $params_array[] = trim($arg_array['bigCate']) ;
        }
       
        //商品上下架
        if (isset($arg_array['forsale']) && $arg_array['forsale'] != 0) {
            $sql .= ' AND forsale = ?';
            $params_type .= 'i';
            
            if($arg_array['forsale'] == 1)
            	$params_array[] = 1 ;
            elseif($arg_array['forsale'] == 2)
            	$params_array[] = 0 ;
        }
		
        //商品是否已经发布
        if (isset($arg_array['isPublish']) && $arg_array['isPublish'] != 0) {
            $sql .= ' AND isPublish=?';
            $params_type .= 'i';
            
            if($arg_array['isPublish'] == 1)
            	$params_array[] = 1 ;
            elseif($arg_array['isPublish'] == 2)
            	$params_array[] = 0 ;
        }
        
        //商品中分类
        if (isset($arg_array['midCate']) && $arg_array['midCate'] != 0) {
            $sql .= ' AND midCategoryID = ?';
            $params_type .= 'i';
            $params_array[] = trim($arg_array['midCate']) ;
        }

        //商品小分类
        if (isset($arg_array['smallCate']) && $arg_array['smallCate'] != 0) {
            $sql .= ' AND smallCategoryID = ?';
            $params_type .= 'i';
            $params_array[] = trim($arg_array['smallCate']) ;
        }

        //商品名称
        if (isset($arg_array['goodsName']) && trim($arg_array['goodsName']) != '') {
            $sql .= ' AND goodsName LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . trim($arg_array['goodsName']) . '%';
        }

        //商品开始价格
        if (isset($arg_array['startPrice']) && trim($arg_array['startPrice']) != '') {
            $sql .= ' AND salePrice >= ?';
            $params_type .= 'd';
            $params_array[] = trim($arg_array['startPrice']) ;
        }

        //商品结束价格
        if (isset($arg_array['endPrice']) && trim($arg_array['endPrice']) != '') {
            $sql .= ' AND salePrice <= ?';
            $params_type .= 'd';
            $params_array[] = trim($arg_array['endPrice']) ;
        }

        //品牌
        if (isset($arg_array['brandID']) && $arg_array['brandID'] != 0) {
            $sql .= ' AND brandID = ?';
            $params_type .= 'i';
            $params_array[] = trim($arg_array['brandID']) ;
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计促销行数
                $search_sql  = 'SELECT COUNT(*) count FROM goods_list_edit WHERE 1=1 ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count  = $count_array[0]->count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询商品促销信息
            $search_sql = 'SELECT * FROM goods_list_edit WHERE 1=1 ' . $sql;

            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            return $temp_item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }
    }
	
	/**
	 * 商品上下架操作
	 *
	 */
	public function goodsForsale ($arg_array) {
		//检查参数
		if (!isset($arg_array['postID_str']) || $arg_array['forsale'] == '')
            return array( 'code' => 400, 'message' => '缺少参数' );
            
		//参数切割成字符串
        $str_array = explode('_', $arg_array['postID_str']);
        $forsale   = $arg_array['forsale'] ;
        
        //检查是否已经选择了商品
        if(!$str_array && $forsale == 1) 
        	return array( 'code' => 400, 'message' => '请选择要上架的商品' );
        else if(!$str_array && $forsale == 0) 
        	return array( 'code' => 400, 'message' => '请选择要下架的商品' );
        
        
		foreach ($str_array as &$twoPostID) {
			 //检查商品是否已经存在 
			try{
	       		$goodsInfo = new entity('goods_list_edit');
	        	$goodsInfo->postID = $twoPostID ;
	       		if ($this->dbca->fetch( $goodsInfo )){
	       			if($goodsInfo->forsale != $forsale) {
	       				//上架二级商品
	       				$this->dbca->stmt_query('UPDATE goods_list_edit SET forsale=?,isPublish=0 , TIMESTAMP=NOW() WHERE postID =? ', 'ii', $forsale,$twoPostID) ;
	       				//上架三级商品信息
	       				$this->dbca->stmt_query('UPDATE goods_sale_edit SET forsale=? , timeStamp=NOW() WHERE twoPostID =? ', 'ii', $forsale,$twoPostID) ;
	       		
	       				//日志处理
	       				$log_array = array('creator' 	  => $arg_array['creator'] ,
	       								   'postID'	 	  => $twoPostID ,
	       								   'goodsID' 	  => $goodsInfo->goodsID ,
	       								   'product_code' => $goodsInfo->product_code,
	       								   'flgType'  	  => 1 ,
	       								   'remark'  	  => sprintf('商品编码「%s」的上下状态已经被「%s」调整为「%d」' ,$goodsInfo->product_code,$arg_array['creator'],$forsale),
	       								   'oldFlg'  	  => $goodsInfo->forsale ,
	       								   'newFlg'  	  => $forsale ) ;
	       								   			   
	       				$this->comm_goods_log ($log_array) ;
	       			}
	       		}
       		}catch (Exception $e) {
	        	 if ($e->getCode() > 0) 
	                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
	            else {
	                error_log($e->getMessage());
	                return array( 'code' => 500, 'message' => '系统错误' );
	            }
	        }
		}
		
		//成功提示信息
		if($forsale == 1)
	    	return array( 'code' => 200, 'message' => sprintf('商品上架成功',$str_array[0]) );           
		else if ($forsale == 0)
			return array( 'code' => 200, 'message' => sprintf('商品下架成功',$str_array[0]) );	
	}
	
	/**
	 *  商品操作日志 
	 * 
	 * @param unknown_type $arg_array 日志数组
	 */
	public function comm_goods_log ($arg_array) {
		if(!isset($arg_array['creator'] , $arg_array['postID'] ,
				  $arg_array['goodsID'] , $arg_array['oldFlg'] ,
				  $arg_array['newFlg'] , $arg_array['flgType'] ,
				  $arg_array['remark'], $arg_array['product_code'] ) ){
				  	
			return array( 'code' => 400, 'message' => '系统错误');         
		}
		
		//参数列表
		$creator = trim($arg_array['creator']) ;			//操作人
		$postID  = trim($arg_array['postID']) ;				//网购号
		$goodsID = trim($arg_array['goodsID']) ;			//商品号
		$oldFlg  = trim($arg_array['oldFlg']) ;				//老的上架标志 
		$newFlg  = trim($arg_array['newFlg']) ;				//新的上架标志
		$flgType = trim($arg_array['flgType']) ;			//日志类型	
		$remark	 = trim($arg_array['remark']) ;				//日期备注
		$product_code = trim($arg_array['product_code']) ;	//商品编码
		
		//保存日志
		$save_goods_log = new entity('log_goods') ;
		$save_goods_log->creator 	  = $creator ;
		$save_goods_log->postID  	  = $postID ;
		$save_goods_log->goodsID 	  = $goodsID ;
		$save_goods_log->product_code = $product_code ;
		$save_goods_log->oldFlg  	  = $oldFlg ;
		$save_goods_log->newFlg  	  = $newFlg ;
		$save_goods_log->flgType 	  = $flgType ;
		$save_goods_log->remark  	  = $remark ;
		$this->dbca->save($save_goods_log , 'goods') ;
		
		return array( 'code' => 200, 'message' => '商品日志保存成功');  
	}
	
	/**
	 * 添加商品评价
	 * @param array  $params 参数数组
	 * @param int    $params['bill_no']      订单号
	 * @param int    $params['postID']       网购号
	 * @param string $params['content']      评价内容
	 * @param int    $params['commentLevel'] 评分
	 * @param int    $params['pcustID']      客户号
	 * @param string $params['operator']     操作人
	 * @param object $dbca                   数据库实例
	 * @return -1：评分未选择
	 *         -2：评价内容为空
	 *         -3：订单商品不存在
	 *         -4：订单商品已评价过
	 *         -5：商品信息不存在
	 *		 -100：参数错误
	 *		 -101：系统错误
	 *          1：保存成功
	 */
	public function addGoodsComment($params) {
		
		//检查参数
		if (!isset($params['bill_no'], $params['postID'], $params['content'], $params['pcustID'],$params['operator']) || !is_numeric($params['postID']) || !is_numeric($params['pcustID']))
			return array( 'code' => 400, 'message' => '参数错误' );
		
		if (!isset($params['commentLevel']) || !in_array($params['commentLevel'], array(1, 2, 3, 4, 5)))
			return array( 'code' => 400, 'message' => '请选择评分' );
		if (empty($params['content']))
			return array( 'code' => 400, 'message' => '请填写评价内容' );
			
		//定义变量
		$bill_no = $params['bill_no'];								//订单号
		$postID = $params['postID'];								//网购号
		$content = htmlspecialchars(trim($params['content']));		//评价内容
		$commentLevel = $params['commentLevel'];					//评分
		$pcustID = $params['pcustID'];								//客户号
		$operator = $params['operator'];							//操作人
		$nowTime = date(G_DEFAULT_DATETIME_FORMAT);					//当前时间
		
		try {
			
			//查询订单商品
			$sql = 'SELECT comment_flg,uuid FROM bill_goods WHERE bill_no = ? AND goods_postID = ?';
			$bill = &$this->dbca->stmt_query( $sql, 'si', array( $bill_no, $postID ));
			
			//订单商品不存在
			if (!$bill)
				throw new Exception( '订单商品不存在' , -1000);
			//订单商品已评价
			if ($bill[0]->comment_flg == 1)
				throw new Exception( '订单商品已评价', -1000);
			
			//查询商品信息
			$sql = 'SELECT goodsID,postID,twoPostID,goodsName FROM goods_sale WHERE postID = ?';
			$goods =&$this->dbca->stmt_query( $sql, 'i', $postID );
			
			//商品信息不存在
			if (!$goods)
				throw new Exception( '商品信息不存在', -1000 );
				
			$goods = $goods[0];
			$goods->goodsLink = $this->setLink($goods->uid);
			
			//获取用户头像
			$sql = 'SELECT head_pic,sexy FROM cust_master WHERE pcustID = ?';
			$goodsIDResult = &$this->dbca-> stmt_query($sql,'i',$pcustID);
			
			if (!$goodsIDResult || empty($goodsIDResult[0]->head_pic)) {
				if ($goodsIDResult[0]->sexy == 2) {
					$custHeaderPic = 'member_wlogo.gif';
				} else {
					$custHeaderPic = 'member_logo.gif';
				}
			} else {
				$custHeaderPic = $goodsIDResult[0]->head_pic;
			}
			
			//保存评价信息
			$content_comments = new entity('content_comments');
			$content_comments->pcustID = $pcustID;
			$content_comments->bill_no = $bill_no;
			$content_comments->postID = $postID;
			if ($this->dbca->fetch($content_comments)) {
				throw new Exception( '订单商品已评价', -1000 );
			}
			$content_comments->creator = $operator;
			$content_comments->custHeaderPic = $custHeaderPic;
			$content_comments->commentInfo = $content;
			$content_comments->goodsID = $goods->goodsID;
			$content_comments->postID = $goods->postID;
			$content_comments->goodsName = $goods->goodsName;
			$content_comments->goodsLink = $goods->goodsLink;
			$content_comments->ipAddress = $_SERVER['REMOTE_ADDR'];
			$content_comments->commentLevel = $commentLevel;
			$content_comments->twoPostID = $goods->twoPostID;
			$content_comments->bill_no = $bill_no;
			$this->dbca->save($content_comments, 'member');
			
			//更新订单商品信息
			$sqlstr = 'UPDATE pa_bill_goods SET comment_flg = 1 WHERE uuid = "' . $bill[0]->uuid . '"';
			$dbca->execute($sqlstr);
			
			return array( 'code' => 200, 'message' => '商品评价保存成功' );
			
			
		} catch (Exception $e) {
			if ($e->getCode() == -1000) {
				return array( 'code' => 400, 'message' => $e->getMessage() );
			} else {
				return array( 'code' => 500, 'message' => '系统错误，请联系网站管理员' );
			}
		}
	}

    public function uploadImg($goodsID , $fileName , $uploadfileName , $dateDir , $thumb_flg = 0){

        $savePath = G_APPLICATION_BASEPATH . 'quanliadmin/docroot/images/goods/';
        $tmpPath = G_APPLICATION_BASEPATH . 'quanliadmin/docroot/images/temp/image/' . date('Ymd') . '/';

        if(!file_exists($tmpPath . '/'))
            mkdir($tmpPath . '/' , 0777);

        if(!file_exists($savePath . $dateDir . '/' . $goodsID . '/'))
            mkdir($savePath . $dateDir . '/'. $goodsID . '/' , 0777);

        //防止页面刷新
        if(!file_exists($tmpPath . $uploadfileName))
            return $dateDir . '/' . $goodsID . '/' . $fileName;

        if(($savePath . $dateDir . '/' . $goodsID . '/' . $fileName))
            @unlink($savePath . $dateDir . '/' . $goodsID . '/' . $fileName);

        //将图片移动到指定目录
        copy($tmpPath . $uploadfileName , $savePath . $dateDir . '/' . $goodsID . '/' . $fileName);

        if($thumb_flg == 1){
            //生成缩略图
            $src_file = $savePath . $dateDir . '/' . $goodsID . '/' . $fileName;
            $dest_file = $savePath . $dateDir . '/'.$goodsID . '/' . 'thumb_' . $fileName;

            if(!$this->ResizeImage($src_file, $dest_file))
                error_log(sprintf('商品号「%s」生成缩略图失败',$goodsID));

        }

        return $dateDir . '/' . $goodsID . '/' . $fileName;
    }

    /**
     * 图片缩略图
     *
     * @param  $src_file	源图片名称
     * @param  $dest_file	目标图片名称
     * @param  $new_size	图片的大小
     * @param  $quantity	图片的质量
     * @return unknown
     */
    public function ResizeImage( $src_file="" , $dest_file="" , $new_size = array('width'=>308,'height'=>288) , $quantity="100" ){
        $imginfo = getimagesize( $src_file );
        if ($imginfo == NULL){
            error_log("file name is NULL");
            return false;
        }
        // GD can only handle JPG & PNG images
        if ($imginfo[2] != JPG && $imginfo[2] != PNG && $imginfo[2] != GIF){
            error_log("file is not be supported");
            die("file is not be supported");
            return false;
        }
        $srcWidth = $imginfo[0];
        $srcHeight = $imginfo[1];
        $radio=max(($srcWidth/$new_size['width']),($srcHeight/$new_size['height']));
        $destWidth=(int)$srcWidth/$radio;
        $destHeight=(int)$srcHeight/$radio;
        if ($imginfo[2] == JPG)
            $src_img = imagecreatefromjpeg($src_file);
        elseif($imginfo[2] == PNG){
            $src_img = imagecreatefrompng($src_file);
        }
        else
            $src_img = imagecreatefromgif($src_file);

        if (!$src_img){
            error_log("file type is not found");
            return false;
        }

        $dst_img = imagecreatetruecolor($destWidth, $destHeight);
        imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $destWidth, (int)$destHeight, $srcWidth, $srcHeight);
        if ($imginfo[2] == JPG)
            imagejpeg($dst_img, $dest_file, $quantity);
        elseif($imginfo[2] == PNG)
            imagepng($dst_img, $dest_file);
        else
            imagegif($dst_img, $dest_file);

        imagedestroy($src_img);
        imagedestroy($dst_img);

        // Set mode of uploaded picture
        chmod($dest_file, 0755);
        // We check that the image is valid
        $imginfo = @getimagesize($dest_file);
        if ($imginfo == NULL){
            @unlink($dest_file);
            return false;
        } else {
            return true;
        }
    }

	
	/**
	 * 商品基本信息同步
	 *
	 * @param unknown_type $arg_array
	 */
	public function goodsToSale($arg_array) {
		
		global $G_PGLOB;
		
		//参数检查
		if(!isset($arg_array['postID']) || empty($arg_array['postID'])) {
			return array( 'code' => 400, 'message' => '参数错误' );
		}	
			
		$postID = trim($arg_array['postID']) ;
		$this->dbca->beginTransaction();	
		try {

			//检查商品数据
			$goodsInfo = new entity('goods_list_edit') ;
			$goodsInfo->postID = $postID ;
			if(!$this->dbca->fetch($goodsInfo)){
				$this->dbca->commit();
				return array( 'code' => 400, 'message' => sprintf('待发布商品中不存在网购号「%d」的商品'  , $postID) );
			}
			
			//判断商品发布到商城还是指定店铺中
			$shopArray = explode(',', $goodsInfo->shopStr);
			if ($shopArray) {
				foreach ($shopArray as $shop) {
					if ($shop == 1) {
						//检查商品是否已经存在待发布商品中
						$issetSalegoods = new entity('goods_list') ;
						$issetSalegoods->postID = $postID ;
						if(!$this->dbca->fetch($issetSalegoods)) {
							//将二级商品移动到二级销售商品表中
							$this->dbca->stmt_query( 
								'INSERT INTO `goods_list`
								(`uuid`,`timeStamp`,`creator`,`createTime`,`goodsID`,`goodsName`,`postID`,`mainPostID`,`bigCategoryID`, `bigCategoryName`,`midCategoryID`,
								`midCategoryName`,`smallCategoryID`,`smallCategoryName`,`forsale`,`spec`,`useFlg`,`marketPrice`,`salePrice`,`pointsByFlg`,`pointPrice`,
								`addPoints`,`salePoints`,`discountFlg`,`editor`, `brief`,`brandID`,`brandName`,`unitID`,`unitName`,`description`,tid,templates,`goodsMainPic`,`memo`,
								`uid`, `product_code`,`product_mainID`,`discount`,`saletotal`,`site_id`,`shelfLife`) 
								 
								 SELECT `uuid`,NOW(), `creator`,`createTime`,`goodsID`, `goodsName`,
								 `postID`,`mainPostID`,`bigCategoryID`,`bigCategoryName`,`midCategoryID`, `midCategoryName`,`smallCategoryID`,`smallCategoryName`,
								 forsale ,`spec`,useFlg ,`marketPrice`,`salePrice`,`pointsByFlg`,`pointPrice`,`addPoints`,`salePoints`,`discountFlg`,`editor`,`brief`,`brandID`,
								 `brandName`,`unitID`,`unitName`,`description`,tid,templates,`goodsMainPic`,`memo`, `uid`,`product_code`,`product_mainID`,ROUND(salePrice/marketPrice,2),
								 0,`site_id`,`shelfLife` FROM `goods_list_edit` WHERE postID=? ', 'i', $postID );
							
							//将三级商品移动到三级销售表中
							$this->dbca->stmt_query(
								'INSERT INTO `goods_sale`(`uuid`,`timeStamp`,`creator`,`createTime`, `goodsID`,`goodsName`,`postID`, `mainPostID`,
								`bigCategoryID`,`bigCategoryName`,`midCategoryID`,`midCategoryName`, `smallCategoryID`,`smallCategoryName`,`forsale`, `spec`,
								`useFlg`, `marketPrice`,`salePrice`, `pointPrice`,`addPoints`,`salePoints`,`discountFlg`, `pointsByFlg`,`brandID`,`brandName`,
								`unitID`,`unitName`,`editor`,`brief`,`description`,tid,templates,`goodsMainPic`,`memo`,`goodsLength`,`goodsWidth`,`goodsHeight`,`goodsWeight`,
								`barcode`,`product_code`,`product_mainID`,`twoPostID`, `site_id`,`shelfLife`)
								             
								 SELECT `uuid`,NOW(),`creator`,`createTime`,`goodsID`, `goodsName`, `postID`,`mainPostID`, `bigCategoryID`,`bigCategoryName`,`midCategoryID`,`midCategoryName`,
								`smallCategoryID`, `smallCategoryName`, forsale ,`spec`, useFlg ,`marketPrice`,`salePrice`,`pointPrice`,`addPoints`,`salePoints`,`discountFlg`,`pointsByFlg`,`brandID`,
								`brandName`, `unitID`, `unitName`,`editor`,`brief`,`description`,tid,templates,`goodsMainPic`, `memo`,`goodsLength`,`goodsWidth`,`goodsHeight`, `goodsWeight`,`barcode`,
								`product_code`,`product_mainID`,`twoPostID`,`site_id`,`shelfLife` FROM `goods_sale_edit` WHERE twoPostID=?' , 'i' , $postID) ;
							
						}else{
							
							//同步待发布二级商品信息到销售二级商品信息
							$this->dbca->stmt_query( 
								'UPDATE `goods_list` gl, `goods_list_edit` gle 
								SET gl.timeStamp=NOW(),gl.goodsName=gle.goodsName ,gl.bigCategoryID=gle.`bigCategoryID`,gl.bigCategoryName=gle.`bigCategoryName`,
								gl.midCategoryID=gle.midCategoryID,gl.midCategoryName=gle.midCategoryName,gl.smallCategoryID=gle.smallCategoryID,gl.smallCategoryName=gle.smallCategoryName,
								gl.spec=gle.spec,gl.marketPrice=gle.marketPrice,gl.salePrice=gle.salePrice,gl.pointsByFlg=gle.pointsByFlg,gl.pointPrice=gle.pointPrice,
								gl.pointPrice=gle.pointPrice,gl.salePoints=gle.salePoints,gl.discountFlg=gle.discountFlg,gl.editor=gle.editor,gl.brief=gle.brief,
								gl.brandID=gle.brandID,gl.brandName=gle.brandName,gl.unitID=gle.unitID,gl.unitName=gle.unitName,gl.description=gle.description,
								gl.tid=gle.tid,gl.templates=gle.templates,gl.goodsMainPic=gle.goodsMainPic,gl.memo=gle.memo,gl.discount=ROUND(gle.salePrice/gle.marketPrice,2),gl.site_id=gle.site_id,
								gl.forsale=gle.forsale,gl.useFlg=gle.useFlg,gl.shelfLife=gle.shelfLife
								WHERE gl.`postID`=gle.`postID` AND gle.`postID`=?' , 'i' , $postID) ;
							
							//同步待发布三级商品信息到销售三级商品信息
							$this->dbca->stmt_query( 
								'UPDATE `goods_sale` gs,`goods_sale_edit` se 
								SET gs.timeStamp=NOW(),gs.goodsName=se.goodsName,gs.bigCategoryID=se.bigCategoryID,gs.bigCategoryName=se.bigCategoryName,
								gs.midCategoryID=se.midCategoryID,gs.midCategoryName=se.midCategoryName,gs.smallCategoryID=se.smallCategoryID,
								gs.smallCategoryName=se.smallCategoryName,gs.spec=se.spec,gs.marketPrice=se.marketPrice,gs.salePrice=se.salePrice,
								gs.pointPrice=se.pointPrice,gs.addPoints=se.addPoints,gs.salePoints=se.salePoints,gs.discountFlg=se.discountFlg,
								gs.pointsByFlg=se.pointsByFlg,gs.brandID=se.brandID,gs.brandName=se.brandName,gs.unitID=se.unitID,gs.unitName=se.unitName,
								gs.editor=se.editor,gs.brief=se.brief,gs.description=se.description,gs.goodsMainPic=se.goodsMainPic,gs.memo=se.memo,
								gs.goodsLength=se.goodsLength,gs.goodsWidth=se.goodsWidth,gs.goodsHeight=se.goodsHeight,gs.goodsWeight=se.goodsWeight,
								gs.barcode=se.barcode,gs.site_id=se.site_id ,gs.tid=se.tid,gs.templates=se.templates ,
								gs.forsale=se.forsale,gs.useFlg=se.useFlg,gs.shelfLife=se.shelfLife
								WHERE gs.`postID`=se.`postID` AND se.`twoPostID`=?' ,'i' ,$postID ) ;
						}
					} else {
							
						$saveXshopGoods = new entity('3rd_goods_relation') ;
						$saveXshopGoods->product_code = $goodsInfo->product_mainID;
						$saveXshopGoods->shopID       = $shop;
						if (!$this->dbca->fetch($saveXshopGoods)) {
							$saveXshopGoods->creator = $G_PGLOB->currentUserID;
						}
						$saveXshopGoods->product_code = $goodsInfo->product_mainID;
						$saveXshopGoods->goodsName 	  = $goodsInfo->goodsName;
						$saveXshopGoods->bigCate      = $goodsInfo->bigCategoryID;
						$saveXshopGoods->midCate      = $goodsInfo->midCategoryID;
						$saveXshopGoods->smallCate    = $goodsInfo->smallCategoryID;
						$saveXshopGoods->marketPrice  = $goodsInfo->marketPrice;
						$saveXshopGoods->salePrice    = $goodsInfo->salePrice;
						$saveXshopGoods->numbers      = 1;
						$saveXshopGoods->newFlg       = 'new';
						$saveXshopGoods->onsale       = 'onsale';
						$saveXshopGoods->feePayer     = 'seller';
						$saveXshopGoods->post_fee     = '0';
						$saveXshopGoods->express_fee  = '0';
						$saveXshopGoods->ems_fee      = '0';
						$saveXshopGoods->sub_stock    = '1';
					
						$this->dbca->save($saveXshopGoods);
						
						//生成xshop日志操作
						$saveGoodsLog = new entity('3rd_goods_log') ;
						$saveGoodsLog->product_code = $goodsInfo->product_mainID;
						$saveGoodsLog->creator = $G_PGLOB->currentUserID;
						$saveGoodsLog->shopID  = $shop;
						$this->dbca->save($saveGoodsLog ,'3rd');
						
					}
				}
			}

			$goodsInfo->isPublish = 1;
			$this->dbca->save($goodsInfo , '3rd') ;
	
			$this->dbca->commit();
			return array('code' => 200, 'message' => '商品信息同步成功');
		} catch (Exception $e) {
			$this->dbca->commit();
			if ($e->getCode() == -1000)
				return array('code' => 400, 'message' => $e->getMessage());
			else{
				error_log($e->getMessage());
				return array('code' => 500, 'message' => '系统错误，请联系网站管理员');
			}
		}	
	}
		
	/**
	 * 获取规格信息
	 *
	 * @param 参数数组 array $arg_array
	 */
	public function getSpecInfo($arg_array){	
		if(!isset($arg_array['groupID']))
			return array( 'code' => 400, 'message' => '缺少参数' );
			
		//规格组ID	
		$groupID = trim($arg_array['groupID']);
		if(!is_numeric($groupID) || intval($groupID) <= 0)
			return array( 'code' => 400, 'message' => '参数错误' );
			
		$specData = $this->dbca->stmt_query(sprintf('SELECT specID,specName FROM goods_spec WHERE useFlg = 1 AND specGroupID = %s', $groupID));
		$groupArr = array();
		if($specData){
			foreach ($specData as $data){
				$groupArr[$data->specID] = $data->specName;
			}
		}

		return array( 'code' => 200, 'message' => $groupArr);
	}
	
	/**
	 * 商品录入
	 *
	 * @param array 参数数组 $arg_array
	 */
	public function addGoods($arg_array){

		$commHandler = new commHandler( $this->dbca );

		//基本参数校验
		if (empty($arg_array) || !isset($arg_array['goodsBase']) || !isset($arg_array['goodsCategory'])) {
			return array('code' => 400, 'message' => '缺少参数');
		}
		
		$goodsBase     	= $arg_array['goodsBase'];	//商品基本信息
		$goodsCategory	= $arg_array['goodsCategory'];	//商品分类
		$goodsImg       = isset($arg_array['goodsImg']) ? $arg_array['goodsImg'] : null;	//图片
		$goodsKey   	= isset($arg_array['goodsKeyWord']) ? $arg_array['goodsKeyWord'] : null;	//关键字
		$goodsTag	    = isset($arg_array['goodsTag']) ? $arg_array['goodsTag'] : null;	//标签
		$goodsExtend	= isset($arg_array['goodsExtend']) ? $arg_array['goodsExtend'] : null;	//扩展属性
		
		if (empty($goodsBase) || empty($goodsCategory)) {
			return array('code' => 400, 'message' => '商品基本资料不完整，请核实');
		}
		
		//************************************ 表单参数校验 开始 *************************************//
		$error_msg = '';
		
		//商品名称
        if (isset($goodsBase['goodsName']) && !empty($goodsBase['goodsName'])) {
            $goodsName  = trim($goodsBase['goodsName']);
        }else {
            $error_msg .= '商品名称不能为空<br/>';
        }    
		
		//商品品牌
		$brandName = '';
		if (isset($goodsBase['brandID']) && !empty($goodsBase['brandID'])) {
            $brandID  = $goodsBase['brandID'];
        }else {
            $brandID = 0;
        } 
 
        if (!empty($brandID)) {
                
            //获取品牌名称
            $goods_brand = new entity('goods_brand');
            $goods_brand->brandID = $brandID;
            $goods_brand->useFlg  = 1;
            if($this->dbca->fetch($goods_brand)){
            	
            	$brandName = $goods_brand->brandName;
            	
            }else {
            	$error_msg .= '品牌信息不存在或已禁用，请核实<br/>';
            }	
        }
		
		//商品单位
		$unitName = '';
		if (isset($goodsBase['unitID']) && !empty($goodsBase['unitID'])) {
            $unitID  = $goodsBase['unitID'];
        }else {
            $unitID = 0;
        } 
 
        if (!empty($unitID)) {
                
            //获取单位名称
            $goods_unit = new entity('goods_unit');
            $goods_unit->unitID = $unitID;
            $goods_unit->useFlg = 1;
            if($this->dbca->fetch($goods_unit)){
            	
            	$unitName = $goods_unit->unitName;
            	
            }else {
            	$error_msg .= '单位信息不存在或已禁用，请核实<br/>';
            }	
        }
        
        //店铺信息
        $shopStr = '';
        if (!isset($goodsBase['shopID']) || empty($goodsBase['shopID'])) {
        	$error_msg .= '请选择店铺信息<br/>';
        } else {
        	foreach ($goodsBase['shopID'] as $shop) {
        		$shopStr .= $shop . ',';
        	}
        	
        	$shopStr = substr($shopStr, 0, -1);
        }
        
        //市场价
        if (isset($goodsBase['marketPrice']) && $commHandler->isMoney($goodsBase['marketPrice'], 1)) {
            $marketPrice = trim($goodsBase['marketPrice']);
        }else {
            $error_msg .= '请输入正确的商品市场价<br/>';
        }
        
        //销售价
        if (isset($goodsBase['salePrice']) && $commHandler->isMoney($goodsBase['salePrice'], 1)) {
            $salePrice = trim($goodsBase['salePrice']);
        }else {
            $error_msg .= '请输入正确的商品销售价<br/>';
        }
        
        //商品重量
        if (isset($goodsBase['goodsWeight']) && is_numeric($goodsBase['goodsWeight'])) {
            $goodsWeight = trim($goodsBase['goodsWeight']);
        }else {
            $error_msg .= '请输入正确的商品重量<br/>';
        }
        
        //商家编码
        if (isset($goodsBase['externalNo']) && !empty($goodsBase['externalNo'])) {
            $externalNo = trim($goodsBase['externalNo']);
        }else {
            $error_msg .= '请输入商家编码<br/>';
        }
        
        //分类
        if(isset($goodsBase['bigCategoryID_1']) && !empty($goodsBase['bigCategoryID_1'])){
        	
        	$bigCategoryID = trim($goodsBase['bigCategoryID_1']);
        	
        	//获取大分类名称
        	$bigName = new entity('goods_bigcategory');
        	$bigName->bigCategoryID = $bigCategoryID;
        	$bigName->useFlg        = 1;
        	if($this->dbca->fetch($bigName)){	
        		
        		$bigName = $bigName->description;
        		
        	}else {
        		$error_msg .= '大分类信息不存在或已禁用，请核实<br/>';	
        	}		
        		
        	//中分类
        	if(isset($goodsBase['midCategoryID_1']) && !empty($goodsBase['midCategoryID_1'])){
        		
        		$midCategoryID = trim($goodsBase['midCategoryID_1']);
        		
        		//获取中分类名称
        		$midName = new entity('goods_midcategory');
	        	$midName->bigCategoryID = $bigCategoryID;
	        	$midName->midCategoryID = $midCategoryID;
	        	$midName->useFlg        = 1;
	        	if($this->dbca->fetch($midName)){
	        
        			$midName = $midName->description;
	        		
	        	} else {
	        		$error_msg .= '中分类信息不存在或已禁用，请核实<br/>';	
	        	}	
	        		
	        	//小分类
	        	if(isset($goodsBase['smallCategoryID_1']) && !empty($goodsBase['smallCategoryID_1'])){	
	        		
	        		$smallCategoryID = trim($goodsBase['smallCategoryID_1']);
	        		
	        		//获取中分类名称
	        		$smallName = new entity('goods_smallcategory');
		        	$smallName->bigCategoryID   = $bigCategoryID;
		        	$smallName->midCategoryID   = $midCategoryID;
		        	$smallName->smallCategoryID = $smallCategoryID;
		        	$smallName->useFlg          = 1;
		        	if($this->dbca->fetch($smallName)){
		        		
		        		$smallName = $smallName->description;
		        			
		        	} else {
		        		$error_msg .= '小分类信息不存在或已禁用，请核实<br/>';	
		        	}	
	        	}else{ 
	        		$smallCategoryID = 0;	
	        		$smallName       = '';
	        	}			
        	} else {
        		$error_msg .= '请选择商品中分类<br/>';
        	}	
        	
        } else {
        	$error_msg .= '请选择商品大分类<br/>';
        }	
        
        //库存
        $goodsStock = isset($goodsBase['goodsStock']) && !empty($goodsBase['goodsStock']) ? trim($goodsBase['goodsStock']) : 0;
        
        //商品保质期
        $shelfLife = isset($goodsBase['shelfLife']) ? trim($goodsBase['shelfLife']) : '';
        
        //商品简述
        $brief = isset($goodsBase['brief']) ? trim($goodsBase['brief']) : '';
        
        //商品备注
        $memo = isset($goodsBase['memo']) ? trim($goodsBase['memo']) : '';
        
        //详情描述
        $editor = isset($goodsImg['description']) ? trim($goodsImg['description']) : null;

        if(!empty($error_msg)) {
        	return array('code' => 400, 'message' => $error_msg);
        }	

        //************************************ 生成商品信息 开始 *************************************//
        
        $save_goods_array 		= array();		//保存商品数组
        $goods_store_array  	= array();		//库存数组，对应到三级
        $goods_picture_array    = array();		//图片数组，对应到二级
        $goods_keyword_array    = array();		//关键字数组，对应到二级
        $goods_tag_array    	= array();		//标签数组，对应到二级
        $goods_extend_array 	= array();		//扩展属性数组，对应到二级
        $goods_code_array 		= array();		//商品外部编码数组，对应到三级
        $goods_category_array   = array();		//商品对应分类，对应到二级
        $two_uid            	= 0;			//把第一个生成的三级uid保存到二级商品表中
        
        //主网购号  
		$mpostID = $commHandler->generate_seqno('seqno_post');
        
		//先生成二级商品信息
		$two_goodsID = $commHandler->generate_seqno('seqno_goods');
		
		$two_postID = $commHandler->generate_seqno('seqno_post');
		
		$two_goods_obj = new entity('goods_list');
        $two_goods_obj->creator 		  = $arg_array['creator'];
        $two_goods_obj->goodsID           = $two_goodsID;
        $two_goods_obj->goodsName         = $goodsName;
        $two_goods_obj->postID            = $two_postID;
        $two_goods_obj->mainPostID        = $mpostID;
        $two_goods_obj->bigCategoryID     = $bigCategoryID;
        $two_goods_obj->bigCategoryName   = $bigName;
        $two_goods_obj->midCategoryID     = $midCategoryID;
        $two_goods_obj->midCategoryName   = $midName;
        $two_goods_obj->smallCategoryID   = $smallCategoryID;
        $two_goods_obj->smallCategoryName = $smallName;
        $two_goods_obj->spec  			  = '';
        $two_goods_obj->marketPrice  	  = $marketPrice;
        $two_goods_obj->salePrice  	  	  = $salePrice;
        $two_goods_obj->pointsByFlg  	  = 1;
        $two_goods_obj->pointPrice  	  = 0;
        $two_goods_obj->addPoints  	      = 0;
        $two_goods_obj->salePoints  	  = round($salePrice, 0);
        $two_goods_obj->discountFlg  	  = 1;
        $two_goods_obj->brief  	          = $brief;
        $two_goods_obj->brandID  	      = $brandID;
        $two_goods_obj->brandName  	      = $brandName;
        $two_goods_obj->unitID  	      = $unitID;
        $two_goods_obj->unitName  	      = $unitName;
        $two_goods_obj->description  	  = $editor;
        $two_goods_obj->goodsMainPic  	  = '';
        $two_goods_obj->memo         	  = $memo;
        $two_goods_obj->uid         	  = 0;
        $two_goods_obj->product_code      = $two_postID;
        $two_goods_obj->product_mainID    = $mpostID;
        $two_goods_obj->site_id           = 1;
        $two_goods_obj->shelfLife         = $shelfLife;
        $two_goods_obj->shopStr           = $shopStr;
		
		//图片数组
        $goods_picture = new entity('goods_picture');
        $goods_picture->creator = $arg_array['creator'];
        $goods_picture->postID  = $two_postID;
        $goods_picture->goodsID = $two_goodsID;
        $goods_picture_array[]  = $goods_picture;
        
        //关键字数组
        $goods_keyword = new entity('goods_keyword');
        $goods_keyword->creator      = $arg_array['creator'];
        $goods_keyword->postID       = $two_postID;
        $goods_keyword->goodsID      = $two_goodsID;
        $goods_keyword->product_code = $two_postID;
        $goods_keyword_array[]       = $goods_keyword;

        //商品扩展属性
        $goods_extend = new entity('goods_extend');
        $goods_extend->creator		= $arg_array['creator'];
        $goods_extend->postID		= $two_postID;
        $goods_extend->goodsID		= $two_goodsID;
        $goods_extend->product_code	= $two_postID;
        $goods_extend_array[]   	= $goods_extend;
        
        //二级标签数组
        $goods_tag = new entity('goods_tag');
        $goods_tag->creator  = $arg_array['creator'];
        $goods_tag->goodsID  = $two_goodsID;
        $goods_tag->postID   = $two_postID;
        $goods_tag_array[] 	 = $goods_tag;
        
        //商品对应分类
        $goods_category = new entity('goods_category');
        $goods_category->creator  = $arg_array['creator'];
        $goods_category->goodsID  = $two_goodsID;
        $goods_category->postID   = $two_postID;
        $goods_category_array[]   = $goods_category;
		
		//再生成三级商品
		$three_goodsID = $commHandler->generate_seqno('seqno_goods');
		
		$three_postID = $commHandler->generate_seqno('seqno_post'); 
		
		$three_goods_obj = new entity('goods_sale');
        $three_goods_obj->creator 			= $arg_array['creator'];
        $three_goods_obj->goodsID 			= $three_goodsID;
        $three_goods_obj->goodsName  		= $goodsName;
        $three_goods_obj->postID  			= $three_postID;
        $three_goods_obj->mainPostID 		= $mpostID;
        $three_goods_obj->bigCategoryID     = $bigCategoryID;
        $three_goods_obj->bigCategoryName   = $bigName;
        $three_goods_obj->midCategoryID     = $midCategoryID;
        $three_goods_obj->midCategoryName   = $midName;
        $three_goods_obj->smallCategoryID   = $smallCategoryID;
        $three_goods_obj->smallCategoryName = $smallName;
        $three_goods_obj->spec  		  	= '';
        $three_goods_obj->marketPrice  	  	= $marketPrice;
        $three_goods_obj->salePrice  	  	= $salePrice;
        $three_goods_obj->pointPrice  	  	= 0;
        $three_goods_obj->addPoints  	  	= 0;
        $three_goods_obj->salePoints  	  	= round($salePrice, 0);
        $three_goods_obj->discountFlg  	  	= 1;
        $three_goods_obj->pointsByFlg  	  	= 1;
        $three_goods_obj->brandID  	        = $brandID;
        $three_goods_obj->brandName  	    = $brandName;
        $three_goods_obj->unitID  	        = $unitID;
        $three_goods_obj->unitName  	    = $unitName;
        $three_goods_obj->description  	    = $editor;
        $three_goods_obj->brief  	  	  	= $brief;
        $three_goods_obj->goodsMainPic  	= '';
        $three_goods_obj->memo  	 	  	= $memo;
        $three_goods_obj->goodsLength  	  	= 0;
        $three_goods_obj->goodsWidth  	  	= 0;
        $three_goods_obj->goodsHeight  	  	= 0;
        $three_goods_obj->goodsWeight  	  	= $goodsWeight;
        $three_goods_obj->product_code    	= $externalNo;
        $three_goods_obj->product_mainID    = $mpostID;
        $three_goods_obj->twoPostID         = $two_postID;
        $three_goods_obj->site_id           = 1;
        $three_goods_obj->shelfLife         = $shelfLife;
        $three_goods_obj->shopStr           = $shopStr;
 
        $save_goods_array[] = $three_goods_obj;
        
        $two_goods_obj->uid = $three_postID;
        $save_goods_array[] = $two_goods_obj;
		
        //三级商家编码
		$goods_code_array = array(
			'creator'      => $arg_array['creator'],
			'postID'       => $three_postID,
			'goodsID'      => $three_goodsID,
			'product_code' => $externalNo,
			'goodsCode'    => $externalNo
		);

		//库存数组
    	$goods_store = new entity('goods_store');
    	$goods_store->creator   = $arg_array['creator'];
    	$goods_store->goodsID   = $three_goodsID;
    	$goods_store->quantity  = $goodsStock;
    	$goods_store_array[]    = $goods_store;
    	
    	//************************************ 生成商品信息 结束 *************************************//
	
        //************************************ 保存商品信息 *************************************//
        $this->dbca->beginTransaction();
        try{
        	
        	//=====================商品信息========================
        	
	        $this->save_new_goods($save_goods_array);
	        
	        //=====================商品映射分类========================
        	
	        $this->save_category_goods($goods_category_array, $goodsCategory);

            //=====================同步库存========================
            
            $this->save_goods_store($shopStr, $goods_store_array);

            //=====================商品外部编码========================

            $this->save_goods_code($goods_code_array);
            
            //=====================商品关键词==========================

            $this->save_goods_keyword($goods_keyword_array,$goodsKey);

            //=====================商品扩展属性==========================
            $this->save_goods_extend($goods_extend_array,$goodsExtend);
            
            //=====================商品标签============================
            
            $this->save_goods_tag($goods_tag_array, $goodsTag);

            //=======================图片处理==========================
            
            if(!empty($goodsImg) && is_array($goodsImg)){
            	unset($goodsImg['description']);
            	if($goods_picture_array){
            		foreach ($goods_picture_array as $i_val){
            			for ($h = 1; $h <= count($goodsImg); $h++){
            				$pic_result = $this->saveGoodsPicture($i_val->postID , $goodsImg['hidImg_'.$h] , $h ,  $i_val->creator);
							if($pic_result['code'] != 200) {
								throw new Exception('商品录入保存图片失败', -1000);
							}	
            			}
            		}
            	}
            }	
        	
			$this->dbca->commit();
			return array('code' => 200, 'message' => '商品录入成功');	
        }catch (Exception $e){
        	$this->dbca->rollBack();		
        	
        	if($e->getCode() == -1000)
        		return array('code' => 400, 'message' => $e->getMessage());
        	else {
        		error_log($e->getMessage());
        		return array('code' => 400, 'message' => '商品录入失败');	
        	}
        }
	}

	/**
	 * 商品录入
	 * @param $arg_array 参数数组
	 */
	public function save_new_goods($arg_array){
		
		if(empty($arg_array) || !is_array($arg_array)) {
			throw new Exception('商品录入缺少参数', -1000);
		}	
			
		foreach ($arg_array as $val){
			if(!isset($val->twoPostID)){	//二级商品
				$save_list = new entity('goods_list_edit');
				$save_list->creator 		  = $val->creator;
                $save_list->goodsID           = $val->goodsID;
                $save_list->goodsName         = $val->goodsName;
                $save_list->postID            = $val->postID;
                $save_list->mainPostID        = $val->mainPostID;
                $save_list->bigCategoryID     = $val->bigCategoryID;
                $save_list->bigCategoryName   = $val->bigCategoryName;
                $save_list->midCategoryID     = $val->midCategoryID;
                $save_list->midCategoryName   = $val->midCategoryName;
                $save_list->smallCategoryID   = $val->smallCategoryID;
                $save_list->smallCategoryName = $val->smallCategoryName;
                $save_list->spec  			  = $val->spec;
                $save_list->marketPrice  	  = $val->marketPrice;
                $save_list->salePrice  	  	  = $val->salePrice;
                $save_list->pointsByFlg  	  = $val->pointsByFlg;
                $save_list->pointPrice  	  = $val->pointPrice;
                $save_list->addPoints  	      = $val->addPoints;
                $save_list->salePoints  	  = $val->salePoints;
                $save_list->discountFlg  	  = $val->discountFlg;
                $save_list->brief  	          = $val->brief;
                $save_list->brandID  	      = $val->brandID;
                $save_list->brandName  	      = $val->brandName;
                $save_list->unitID  	      = $val->unitID;
                $save_list->unitName  	      = $val->unitName;
                $save_list->description  	  = $val->description;
                $save_list->goodsMainPic  	  = $val->goodsMainPic;
                $save_list->memo         	  = $val->memo;
                $save_list->uid         	  = $val->uid;
                $save_list->product_code      = $val->product_code;
                $save_list->product_mainID    = $val->product_mainID;
                $save_list->site_id           = $val->site_id;
                $save_list->shelfLife         = $val->shelfLife;
                $save_list->shopStr           = $val->shopStr;

                $this->dbca->save($save_list);
                
			}else{	//三级商品
				$save_sale = new entity('goods_sale_edit');
				$save_sale->creator 			= $val->creator;
	            $save_sale->goodsID 			= $val->goodsID;
	            $save_sale->goodsName  			= $val->goodsName;
	            $save_sale->postID  			= $val->postID;
	            $save_sale->mainPostID 			= $val->mainPostID;
	            $save_sale->bigCategoryID     	= $val->bigCategoryID;
	            $save_sale->bigCategoryName   	= $val->bigCategoryName;
	            $save_sale->midCategoryID     	= $val->midCategoryID;
	            $save_sale->midCategoryName  	= $val->midCategoryName;
	            $save_sale->smallCategoryID   	= $val->smallCategoryID;
	            $save_sale->smallCategoryName   = $val->smallCategoryName;
	            $save_sale->spec  		  		= $val->spec;
	            $save_sale->marketPrice  	  	= $val->marketPrice;
	            $save_sale->salePrice  	  		= $val->salePrice;
	            $save_sale->pointPrice  	  	= $val->pointPrice;
	            $save_sale->addPoints  	  		= $val->addPoints;
	            $save_sale->salePoints  	  	= $val->salePoints;
	            $save_sale->discountFlg  	  	= $val->discountFlg;
	            $save_sale->pointsByFlg  	  	= $val->pointsByFlg;
	            $save_sale->brandID  	        = $val->brandID;
	            $save_sale->brandName  	    	= $val->brandName;
	            $save_sale->unitID  	        = $val->unitID;
	            $save_sale->unitName  	    	= $val->unitName;
	            $save_sale->description  	    = $val->description;
	            $save_sale->brief  	  	  		= $val->brief;
	            $save_sale->goodsMainPic  		= $val->goodsMainPic;
	            $save_sale->memo  	 	  		= $val->memo;
	            $save_sale->goodsLength  	  	= $val->goodsLength;
	            $save_sale->goodsWidth  	  	= $val->goodsWidth;
	            $save_sale->goodsHeight  	  	= $val->goodsHeight;
	            $save_sale->goodsWeight  	  	= $val->goodsWeight;
	            $save_sale->barcode    	  		= $val->barcode;
	            $save_sale->product_code    	= $val->product_code;
	            $save_sale->product_mainID    	= $val->product_mainID;
	            $save_sale->twoPostID         	= $val->twoPostID;
	            $save_sale->site_id          	= $val->site_id;
	            $save_sale->shelfLife          	= $val->shelfLife;
	            $save_sale->shopStr          	= $val->shopStr;

	            $this->dbca->save($save_sale);
			}
		}
	}
	
	/**
	 * 商品录入初始化库存
	 * @param $arg_array 参数数组
	 */
	public function save_goods_store($shopArray, $arg_array){
		
		if(empty($shopArray) || empty($arg_array)) {
			throw new Exception('商品录入时初始化库存失败', -1000);
		}
		
		$wmsStore = explode(',', $shopArray);
		
		foreach ($arg_array as $val){
			foreach ($wmsStore as $store) {
			$goodsstore = new entity('wms_goodsstore');
				$goodsstore->creator 	      = $val->creator;
				$goodsstore->storeID 	      = $store;
				$goodsstore->goodsID 	      = $val->goodsID;
				$goodsstore->enableSaleAmount = $val->quantity;
				$goodsstore->lockAmount 	  = 0;
				$goodsstore->badAmount 		  = 0;
				$goodsstore->lastAmount 	  = 0;
				$goodsstore->shelfID 		  = 1;
				
				$this->dbca->save($goodsstore);
			}
		}
	}
	
	/**
	 * 保存商品对应规格信息
	 * @param $arg_array 参数数组
	 */
	public function save_goods_spec($spec_array){
		if(empty($spec_array) || !is_array($spec_array)) {
			throw new Exception('商品录入规格信息保存失败', -1000);
		}	
			
		$flg = 0;	
		foreach($spec_array as &$spec_l){
		
			//尺码规格
			if (!empty($spec_l->specSizeName)) {
				$goods_spec_relation = new entity('goods_spec_relation');
				$goods_spec_relation->creator             = $spec_l->creator;
				$goods_spec_relation->goodsID             = $spec_l->threeGoodsID;
				$goods_spec_relation->twoPostID           = $spec_l->twoPostID;
				$goods_spec_relation->product_code        = $spec_l->three_product_code;
				$goods_spec_relation->specID              = $spec_l->specSizeID;
				$goods_spec_relation->specName            = $spec_l->specSizeName;
				$goods_spec_relation->spec_sortOrder      = $spec_l->specSize_sortOrder;
				$goods_spec_relation->specGroupID         = $spec_l->specSizeGroupID;
				$goods_spec_relation->specGroupName       = $spec_l->specSizeGroupName;
				$goods_spec_relation->specGroup_sortOrder = $spec_l->specSizeGroup_order;
				
				$this->dbca->save($goods_spec_relation, true);
			}
			
			//颜色规格
			if ($spec_l->specColorID != $flg){
				if (!empty($spec_l->specColorName)) {
					$goods_spec_relation = new entity('goods_spec_relation');
					$goods_spec_relation->creator             = $spec_l->creator;
					$goods_spec_relation->goodsID             = $spec_l->twoGoodsID;
					$goods_spec_relation->twoPostID           = 0;
					$goods_spec_relation->product_code        = $spec_l->two_product_code;
					$goods_spec_relation->specID              = $spec_l->specColorID;
					$goods_spec_relation->specName            = $spec_l->specColorName;
					$goods_spec_relation->spec_sortOrder      = $spec_l->specColor_sortOrder;
					$goods_spec_relation->specGroupID         = $spec_l->specColorGroupID;
					$goods_spec_relation->specGroupName       = $spec_l->specColorGroupName;
					$goods_spec_relation->specGroup_sortOrder = $spec_l->specColorGroup_order;
					
					$this->dbca->save($goods_spec_relation, true);
					$flg = $spec_l->specColorID;
				}
			}
		}
	}
	
	/**
	 * 保存关键字
	 * @param $goods_keyword_array 商品信息数组
	 * @param $goodsKey 关键字数组(自动添加)
	 * @param $keyData 商品编码、sku号
	 * 
	 */
	public function save_goods_keyword($goods_keyword_array, $goodsKey){
		
		if (!empty($goods_keyword_array) && !empty($goodsKey)) {
			
			foreach ($goods_keyword_array as $g_val){
			
				foreach ($goodsKey as $key){
					$goods_keyword = new entity('goods_keyword');
					$goods_keyword->postID       = $g_val->postID;
					$goods_keyword->keyword      = $key;
					if($this->dbca->fetch($goods_keyword))
						continue;
	
					$goods_keyword->creator      = $g_val->creator;
					$goods_keyword->goodsID      = $g_val->goodsID;
					$goods_keyword->product_code = $g_val->product_code;
	
					$this->dbca->save($goods_keyword);
				}
			}
		}
	}

    /**
     * 保存商品扩张属性
     * @param $goods_extend_array 二级商品信息
     * @param $goodsExtend 扩展属性
     *
     */
    public function save_goods_extend($goods_extend_array,$goodsExtend){

    	if (!empty($goods_extend_array) && !empty($goodsExtend)) {
    	
			foreach ($goods_extend_array as $goods) {
				
				$sortOrder = 1;
				
				foreach ($goodsExtend as $extend) {
					$goods_extend = new entity('goods_extend');
					$goods_extend->creator       = $goods->creator;
					$goods_extend->sortOrder     = $sortOrder;
					$goods_extend->postID        = $goods->postID;
					$goods_extend->goodsID       = $goods->goodsID;
					$goods_extend->product_code  = $goods->product_code;
					$goods_extend->name          = $extend[0];
					$goods_extend->value         = $extend[1];
					
					$this->dbca->save($goods_extend);
					
					$sortOrder++;
				}
			}
    	}
    }
	
	/**
	 * 保存商品标签
	 *
	 * @param 二级商品相关网购号、商品编号等信息数组 $goods_tag_array
	 * @param 选中的标签 $tagData
	 */
	public function save_goods_tag($goods_tag_array, $tagData){
		if (!empty($goods_tag_array) && !empty($tagData)) {
			foreach ($goods_tag_array as $goods) {
				foreach ($tagData as $tagStr) {
					
					$tagArray = explode('_', $tagStr);
					
					$goods_tag_group = new entity('goods_tag_group');
					$goods_tag_group->tagGroupID = $tagArray[0];
					
					if ($this->dbca->fetch($goods_tag_group)) {
						$goods_tag = new entity('goods_tag');
						$goods_tag->tagID = $tagArray[1];
						if ($this->dbca->fetch($goods_tag)) {
							$save_goods_tag_relation = new entity('goods_tag_relation');
							$save_goods_tag_relation->postID     = $goods->postID;
							$save_goods_tag_relation->tagGroupID = $tagArray[0];
							$save_goods_tag_relation->tagID		 = $tagArray[1];
							if ($this->dbca->fetch($save_goods_tag_relation)) {
								continue;
							}
							
							$save_goods_tag_relation->creator 			  = $goods->creator;
							$save_goods_tag_relation->goodsID 			  = $goods->goodsID;
							$save_goods_tag_relation->tagName  			  = $goods_tag->tagName;
							$save_goods_tag_relation->tagGroupName  	  = $goods_tag_group->tagGroupName;
							$save_goods_tag_relation->tag_sortOrder  	  = $goods_tag->sortOrder;
							$save_goods_tag_relation->tagGroup_sortOrder  = $goods_tag_group->sortOrder;
							$save_goods_tag_relation->threePostID  		  = 0;
							$save_goods_tag_relation->useFlg  	          = 1;
							
							$this->dbca->save($save_goods_tag_relation);
						}
					}
				}
			}
		}
	
	}
	
    /**
     * 保存商品信息
     *
     * @param 参数数组 array $arg_array
     */
    public function saveGoodsBaseInfo( $arg_array ){

        if( !isset( $arg_array['postID']) || empty( $arg_array['postID'] ) ) {
            return array('message'=>'参数错误' , 'code'=>400);
        }    

        if( !isset( $arg_array['goodsName']) || empty( $arg_array['goodsName'] ) ) {
            return array('message'=>'商品名称不能为空' , 'code'=>400);
        }
        
        if( !isset( $arg_array['shopStr']) || empty( $arg_array['shopStr'] ) ) {
            return array('message'=>'请选择店铺信息' , 'code'=>400);
        }
            
        //实例化公共类
        $commHandler = new commHandler( $this->dbca );

        //接收参数
        $postID       = $arg_array['postID'];
        $goodsName    = $arg_array['goodsName'];
        $brandID      = $arg_array['brandID'];
        $unitID       = $arg_array['unitID'];
        $brief        = $arg_array['brief'];
        $memo         = $arg_array['memo'];
        $shelfLife    = $arg_array['shelfLife'];
        $shopStr      = $arg_array['shopStr'];

        //字符串处理
        $goodsName = $commHandler->getVal( $goodsName );
        $brief     = $commHandler->getVal( $brief );
        $memo      = $commHandler->getVal( $memo );

        //检查商品是否存在
        $check_obj = new entity('goods_list_edit');
        $check_obj->postID = $postID;

        if( !$this->dbca->fetch($check_obj) ){
            return array('message'=>sprintf('网购号「%d」商品不存在' , $postID) , 'code'=>404);
        }

        //查询商品品牌信息
        if( $brandID ){
            $goods_brand_sql = 'SELECT brandName FROM goods_brand WHERE brandID=?';
            $goods_brand     = $this->dbca->stmt_query($goods_brand_sql,'i',$brandID);
            $brandName = $goods_brand[0]->brandName;
        }else{
            $brandName = '';
        }

        //查询商品单位信息
        if( $unitID ){
            $goods_unit_sql = 'SELECT unitName FROM goods_unit WHERE unitID=?';
            $goods_unit     = $this->dbca->stmt_query($goods_unit_sql,'i',$unitID);
            $unitName = $goods_unit[0]->unitName;
        }else{
            $unitName = '';
        }

        $check_obj->goodsName    = $goodsName;
        $check_obj->brandID      = $brandID;
        $check_obj->brandName    = $brandName;
        $check_obj->unitID       = $unitID;
        $check_obj->unitName     = $unitName;
        $check_obj->brief        = $brief;
        $check_obj->memo         = $memo;
        $check_obj->shelfLife    = $shelfLife;
        $check_obj->shopStr      = $shopStr;

        //用于同步更新三级商品信息的暂存数据数组
        $saveParams = array(date('Y-m-d H:i:s'),
                            $goodsName,
                            $brandID,
                            $brandName,
                            $unitID,
                            $unitName,
                            $brief,
                            $memo,
                            $shelfLife,
                            $shopStr,
                            $postID
                        );

        //同步更新三级商品信息
        $third_goods_update = 'UPDATE goods_sale_edit
                               SET timeStamp=?,goodsName=?,brandID=?,brandName=?,unitID=?,unitName=?,brief=?,memo=?,
                               shelfLife=?,shopStr=? WHERE twoPostID=?';


        try{

            //开启事务
            $this->dbca->beginTransaction();

            //保存二级商品信息
            $this->dbca->save( $check_obj );

            //同步更新三级商品信息
            $this->dbca->stmt_query( $third_goods_update ,'ssisisssssi',$saveParams );

            //提交事务
            $this->dbca->commit();

            return array('message'=>'保存成功' , 'code'=>200);

        }catch( Exception $e ){

            //回滚事务
            $this->dbca->rollBack();
            error_log( $e->getMessage() );
            return array('message'=>'系统错误，保存失败' , 'code'=>500);

        }

    }

    /**
     * 保存商品关键字
     * $postID  网购号
     * $arg_array  关键字序列组成的数组  如下：
     *  Array
            (
            [0] => 测试
            [1] => 123
            [2] => 1234
            )
     * $currentUserID  当前操作人
     */
    public function saveGoodsKeyWords( $postID , $arg_array , $currentUserID ){

        if( !isset( $postID ) || empty( $postID ) )
            return array('message'=>'参数错误' , 'code'=>400);

        if( empty($arg_array) )
            return array('message'=>'请输入至少一个关键字' , 'code'=>400);

        if( empty($currentUserID) )
            return array('message'=>'当前操作人不能为空' , 'code'=>400);

        //检查商品是否存在
        $check_obj = new entity('goods_list_edit');
        $check_obj->postID = $postID;

        if( !$this->dbca->fetch($check_obj) ){
            return  array('message'=>sprintf('网购号「%d」商品不存在' , $postID) , 'code'=>404);
        }

        $goodsID = $check_obj->goodsID;
        $product_code = $check_obj->product_code;

        //暂存需要保存的对象
        $objArr = array();

        foreach( $arg_array as $keywords ){

            $keyWords_obj = new entity('goods_keyword');
            $keyWords_obj->goodsID      = $goodsID;
            $keyWords_obj->postID       = $postID;
            $keyWords_obj->product_code = $product_code;
            $keyWords_obj->keyword      = $keywords;
            $keyWords_obj->creator      = $currentUserID;

            $objArr[] = $keyWords_obj;

        }

        //删除该商品原来的关键字
        $delete_sql = 'DELETE FROM goods_keyword WHERE postID = ?';

        try{

            //开启事务
            $this->dbca->beginTransaction();

            //删除原来的关键字
            $this->dbca->stmt_query($delete_sql,'i',$postID);

            //循环保存关键字
            foreach( $objArr as $obj ){
                $this->dbca->save( $obj );
            }

            //开启事务
            $this->dbca->commit();

            return array('message'=>'保存成功' , 'code'=>200);

        }catch ( Exception $e ){

            //开启事务
            $this->dbca->rollBack();
            error_log( $e->getMessage() );
            return array('message'=>'系统错误，保存失败' , 'code'=>500);
        }

    }

    /**
     * 保存商品图片
     *
     * $postID  网购号
     * $picName  上传文件临时文件名
     * $sortOrder  图片排序序号
     * $currentUserID  当前操作人ID
     *
     */
    public function saveGoodsPicture( $postID , $picName , $sortOrder ,  $currentUserID ){

        if( !isset( $postID ) || empty( $postID ) )
            return array('message'=>'参数错误' , 'code'=>400);

        if( empty($sortOrder) )
            return array('message'=>'缺少图片排序参数' , 'code'=>400);

        if( empty($currentUserID) )
            return array('message'=>'当前操作人不能为空' , 'code'=>400);

        //检查商品是否存在
        $goodsInfo = new entity('goods_list_edit');
        $goodsInfo->postID = $postID ;
        if(!$this->dbca->fetch($goodsInfo))
            return array('code' => 404 , 'message' => sprintf('网购号「%d」商品不存在' , $postID));

        $goodsID  = $goodsInfo->goodsID ;


        if( $picName != '' ){

            $dateDir  = date('Ym',strtotime($goodsInfo->createTime));	//文件夹目录
            $savePath = G_APPLICATION_BASEPATH.'quanliadmin/docroot/images/temp/image/' . date('Ymd') . '/' . $picName;	//上传图片目录
            $file_ext = strtolower(substr(strrchr($picName , '.'), 1));

            //图片保存的目录
            if(!file_exists(G_APPLICATION_BASEPATH.'quanliadmin/docroot/images/goods/' . $dateDir . '/' . $goodsID.'/'))
                mkdir(G_APPLICATION_BASEPATH.'quanliadmin/docroot/images/goods/' . $dateDir . '/' . $goodsID . '/' , 0777 , true);

            //主图片处理
            if( $sortOrder == 1 ) {

                $dest_file 	= G_APPLICATION_BASEPATH.'quanliadmin/docroot/images/goods/' . $dateDir . '/' . $goodsID . '/thumb_' . $goodsID . '.' . $file_ext;
                if(file_exists($dest_file))
                    @unlink($dest_file);

                //参数 1.上传图片路径 2.新路径(已重命名)
                if(!$this->ResizeImage($savePath , $dest_file))
                    return array('code' => 400 , 'message' => sprintf('网购号「%d」的主图片生成失败' , $postID)) ;

                $mainPic = $dateDir . '/' . $goodsID . '/thumb_' . $goodsID . '.' . $file_ext;
                
                $this->dbca->stmt_query('UPDATE goods_list_edit SET timeStamp=NOW(),goodsMainPic=? WHERE postID=?' ,'si'  , $mainPic , $postID );
                $this->dbca->stmt_query('UPDATE goods_sale_edit SET timeStamp=NOW(),goodsMainPic=? WHERE twoPostID=?' ,'si'  , $mainPic , $postID);
            }

            //展示图片处理
            $fileName 	 = 'display_' . $goodsID . '_'. $sortOrder . '.'. $file_ext;
            $pictureLink = $this->uploadImg( $goodsID , $fileName, $picName , $dateDir , 1);
        }else{
            $pictureLink = $picName ;
        }

        $obj_pic = new entity('goods_picture');
        $obj_pic->postID    = $postID;
        $obj_pic->goodsID 	= $goodsID;
        $obj_pic->sortOrder = $sortOrder;
        $this->dbca->fetch($obj_pic);
        
        $obj_pic->pictureLink = $pictureLink ;
        $obj_pic->creator     = $currentUserID;

        try{

            $this->dbca->save( $obj_pic );

            return array('message'=>'保存成功' , 'code'=>200);

        }catch(Exception $e){
            error_log( $e->getMessage() );
            return array('message'=>'系统错误,保存失败' , 'code'=>500);
        }

    }

    /**
     * 保存商品调价
     * $arg_array  参数数组
     * $secondGoods_tableName  二级商品表名称
     * $thirdGoods_tableName   与二级商品表对应的三级商品表名称
     */
     public function changeGoodsPrice( $arg_array , $secondGoods_tableName , $thirdGoods_tableName){

         if( !isset( $arg_array['postID'] ) || empty( $arg_array['postID'] ) )
             return array('message'=>'参数错误' , 'code'=>400);

         if( empty($secondGoods_tableName) || empty($thirdGoods_tableName) )
             return array('message'=>'二级表名称和对应的三级表名称不能为空' , 'code'=>400);

         //接收参数
         $postID       = $arg_array['postID'];
         $marketPrice  = isset( $arg_array['marketPrice'] )?$arg_array['marketPrice'] : 0;
         $salePrice    = isset( $arg_array['salePrice'] )?$arg_array['salePrice'] : 0;
         $pointPrice   = isset( $arg_array['pointPrice'] )?$arg_array['pointPrice'] : 0;
         $pointsByFlg  = isset( $arg_array['pointsByFlg'] )?$arg_array['pointsByFlg'] : 0;
         $addPoints    = isset( $arg_array['addPoints'] )?$arg_array['addPoints'] : 0;
         $salePoints   = isset( $arg_array['salePoints'] )?$arg_array['salePoints'] : 0;
         	
         //检查商品是否存在
         $check_obj = new entity($secondGoods_tableName);
         $check_obj->postID = $postID;

         if( !$this->dbca->fetch($check_obj) )
             return array('message'=>sprintf('网购号「%d」商品不存在' , $postID) , 'code'=>404);
		  
         $check_obj->isPublish = 0;

        //日志数组
		$log_array = array('creator' 	  => $arg_array['creator'] ,
						   'postID'	 	  => $postID ,
						   'goodsID' 	  => $check_obj->goodsID ,
						   'product_code' => $check_obj->product_code,
						   'flgType'  	  => 2 ,
						   'oldFlg'  	  => $check_obj->salePrice ,
						   'newFlg'  	  => $salePrice ) ; 
						       

         $check_obj->marketPrice  = $marketPrice;
         $check_obj->salePrice    = $salePrice;
         $check_obj->pointPrice   = $pointPrice;
         $check_obj->pointsByFlg  = $pointsByFlg;
         $check_obj->addPoints    = $addPoints;
         $check_obj->salePoints   = $salePoints;

         //用于同步更新三级商品信息的暂存数据数组
         $saveParams = array(date('Y-m-d H:i:s'),
                             $marketPrice,
                             $salePrice,
                             $pointPrice,
                             $pointsByFlg,
                             $addPoints,
                             $salePoints,
                             $postID
                         );

         //同步更新三级商品信息
         $third_goods_update = 'UPDATE '.$thirdGoods_tableName.' SET timeStamp=?,marketPrice=?,salePrice=?,pointPrice=?,pointsByFlg=?,addPoints=?,salePoints=? WHERE twoPostID=?';

         try{

             //开启事务
             $this->dbca->beginTransaction();

             //保存二级商品信息
             $this->dbca->save($check_obj);

             //同步更新三级商品信息
             $this->dbca->stmt_query( $third_goods_update ,'siiiiiii',$saveParams );

             //提交事务
             $this->dbca->commit();
             
			 //保存商品日志			   
			 $log_array['remark'] = sprintf('操作数据「%s」' , print_r($check_obj, true)) ;
			 $this->comm_goods_log ($log_array) ;
 
             return array('message'=>'保存成功' , 'code'=>200);
				
         }catch( Exception $e ){

             //回滚事务
             $this->dbca->rollBack();
             error_log( $e->getMessage() );
             return array('message'=>'系统错误，保存失败' , 'code'=>500);

         }

     }

   /**
    * 将商品详情描述的图片转化为延迟加载图片
    *
    * @param unknown_type $description		商品详情描述
    * @param unknown_type $suffix			商品图片后缀
    * @return unknown
    */

   	public function descriptionPic($description , $suffix = ''){ 
		preg_match_all ('/(<img )(.[^>]*)(>)/', $description , $matchArray); 
		if(empty($matchArray))
			return $description ;
			
		//被截取的图片正则
		$picArray = $matchArray[0] ;
	
		if(!empty($picArray)){
			foreach ($picArray as &$p_l)  {
				//检查是否已经存在orginalsrc
				if(stripos( $p_l , 'orginalsrc') !== false) 
					continue ;
				
				//将图片打散
				$imgArr  = explode(' ', $p_l) ;
				$imgPath = '' ;
				if($imgArr) {
					foreach ($imgArr as &$i_l) {
						//将src 换成默认的图片路径
						if(stripos( $i_l , 'src') !== false) {
							$imgPath .= ' src="' . G_SHOP_CDN . '/shop/theme/xth2/images/comm/lazyloading.gif" ' ;
							
							//得到图片路径
							$srcArr1  = explode('"' , $i_l) ;
							$srcArr2  = explode("'" , $i_l) ;
							
							if(count($srcArr1) > 1) 
								$srcStr = $srcArr1[1] ;
							else
								$srcStr = $srcArr2[1] ;
							
							if($suffix != '')
								$imgPath .= sprintf(' orginalsrc="%s?%s" ' , $srcStr , $suffix) ;	
							else
								$imgPath .= sprintf(' orginalsrc="%s" ', $srcStr);		
						}else
							$imgPath .= ' ' . $i_l . ' ' ;
					}
				}

				//将图片重新放入到内容中
				$description = str_replace($p_l , $imgPath , $description) ;

			}
		}

		//返回最新的详情
		return $description ;
	}
	
	//得到商品底部详情模板
	public function goodsDetailTemplate (){
		$template = &$this->dbca->stmt_query('SELECT tid,title,description FROM goods_detail_template' );	
		return $template ;
	}
	
	/**
	 * 保存购物须知
	 *
	 */
	public function saveShoppingTips( $params ){
		$title       = isset($params['title']) ? trim($params['title']) : null;
		$description = isset($params['description']) ? trim($params['description']) : null;
		$remark = isset($params['remark']) ? trim($params['remark']) : null;
		$tid         = isset($params['tid']) ? intval(trim($params['tid'])) : null;
		
		if(!isset($params['title']) || !isset($params['description']) || !isset($params['creator']))
			return array( 'code' => 400, 'message' => '参数错误' );
		
		if(empty($title))
			return array( 'code' => 400, 'message' => '模板标题不能为空' );
			
		if(empty($description))
			return array( 'code' => 400, 'message' => '详情描述不能为空' );	
			
		if(!empty($tid)){
			if(!is_numeric($tid) || $tid <= 0)
				return array( 'code' => 400, 'message' => '参数错误' );	
		}
		
		$sys_itemcategory = new entity('sys_itemcategory');
		$sys_itemcategory->itemCategoryName = '购物须知';
		if (!$this->dbca->fetch($sys_itemcategory)) {
			return array( 'code' => 400, 'message' => '该购物须知分类未找到' );	
		}
		
		$sys_item = new entity('sys_item');
		if ($tid) {
			$sys_item->itemID = $tid;
			if (!$this->dbca->fetch($sys_item)) {
				return array( 'code' => 400, 'message' => '该购物须知未找到' );	
			}
		}
		$sys_item->itemName = $params['title'];
		$sys_item->itemCategoryID = $sys_itemcategory->itemCategoryID;
		$sys_item->useFlg = 1;
		$sys_item->extend_1 = $params['remark'];
		$sys_item->extend_2 = $params['description'];
		$this->dbca->save($sys_item);
		
		if(!empty($tid)){
			return array( 'code' => 200, 'message' => '购物须知更新成功' );
		} else {	
			return array( 'code' => 200, 'message' => '购物须知保存成功' );
		}
	}
	
	/**
	 * 删除购物须知
	 *
	 */
	public function deleteShoppingTips($params){
		$delStr = isset($params['delStr']) ? trim($params['delStr']) : null;
		if(empty($delStr))
			return array( 'code' => 400, 'message' => '请选择删除的购物须知' );	
			
		$delInfo = explode('_',$delStr);
		if($delInfo){
			foreach ($delInfo as $delVal){
				$this->dbca->stmt_query('DELETE FROM sys_item WHERE itemID = ? AND itemCategoryID = 12', 'i', $delVal);
			}
		}
		return array( 'code' => 200, 'message' => '购物须知已删除' );	 
	}
	
	/**
	 * 保存详情模板
	 *
	 */
	public function saveDetailSetup($params){
		$title       = isset($params['title']) ? trim($params['title']) : null;
		$description = isset($params['description']) ? trim($params['description']) : null;
		$tid         = isset($params['tid']) ? intval(trim($params['tid'])) : null;
		
		if(!isset($params['title']) || !isset($params['description']) || !isset($params['creator']))
			return array( 'code' => 400, 'message' => '参数错误' );
		
		if(empty($title))
			return array( 'code' => 400, 'message' => '模板标题不能为空' );
			
		if(empty($description))
			return array( 'code' => 400, 'message' => '详情描述不能为空' );	
			
		if(!empty($tid)){
			if(!is_numeric($tid) || $tid <= 0)
				return array( 'code' => 400, 'message' => '参数错误' );	
		}
			
		$goods_template = new entity('goods_detail_template');
		if(!empty($tid)){
			$goods_template->tid = $tid;
			if(!$this->dbca->fetch($goods_template))
				return array( 'code' => 404, 'message' => '详情页模板信息未找到' );
				
			$goods_template->editor  = $params['creator'];
		}else
			$goods_template->creator = $params['creator'];

		$goods_template->title   	   = $title;
		$goods_template->description   = $description;
		
		$this->dbca->save($goods_template, 'goods');
		
		if(!empty($tid))
			return array( 'code' => 200, 'message' => '详情页模板更新成功' );	 
		else	
			return array( 'code' => 200, 'message' => '详情页模板保存成功' );	 
	}
	
	/**
	 * 删除详情页模板
	 *
	 */
	public function deleteDetailSetup($params){
		$delStr = isset($params['delStr']) ? trim($params['delStr']) : null;
		if(empty($delStr))
			return array( 'code' => 400, 'message' => '请选择删除详情页模板' );	
			
		$delInfo = explode('_',$delStr);
		if($delInfo){
			foreach ($delInfo as $delVal){
				$this->dbca->stmt_query('DELETE FROM goods_detail_template WHERE tid = ?', 'i', $delVal);
			}
		}
		return array( 'code' => 200, 'message' => '详情页模板已删除' );	 
	}
	
	//根据标签号获得标签信息和标签组信息
	public function getTagInfo($tagID){
		if(empty($tagID))
			return array( 'code' => 400, 'message' => '参数错误');
		
		$tag_sql = 'SELECT g_Tag.*,g_Group.tagGroupName,g_Group.sortOrder gSortOrder FROM
			(
			SELECT tagID,tagName,tagGroupID,sortOrder FROM goods_tag WHERE tagID = ? AND useFlg = 1) g_Tag
			INNER JOIN goods_tag_group g_Group ON g_Tag.tagGroupID = g_Group.tagGroupID
			WHERE g_Group.useFlg = 1';
		
		$goods_tag = $this->dbca->stmt_query($tag_sql, 'i', $tagID);

		if($goods_tag)
			return array( 'code' => 200, 'message' => $goods_tag[0]);
			
		else 
			return array( 'code' => 400, 'message' => '信息未找到');	
	}

    /**
     * 查询大分类信息
     * @param $arg_array
     * @return array|null
     */
    public function searchBigCategory( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //大分类ID
        if (isset($arg_array['bigCategoryID']) && is_numeric($arg_array['bigCategoryID'])) {
            $sql .= ' AND bigCategoryID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['bigCategoryID'];
        }

        //使用标志
        if (isset($arg_array['useFlg']) && in_array($arg_array['useFlg'], array(0, 1))) {
            $sql .= ' AND useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }


        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计分类数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM goods_bigcategory ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM goods_bigcategory ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {

                $item_array[] = array(
                    'bigCategoryID' => $item->bigCategoryID,
                    'name' => $item->description,
                    'useFlg' => $item->useFlg,
                    'sortOrder' => $item->sortOrder,
                    'link' => $this->setCategoryLink( $item->bigCategoryID )
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 查询中分类信息
     * @param $arg_array
     * @return array|null
     */
    public function searchMidCategory( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //大分类ID
        if (isset($arg_array['bigCategoryID']) && is_numeric($arg_array['bigCategoryID'])) {
            $sql .= ' AND bigCategoryID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['bigCategoryID'];
        }

        //中分类ID
        if (isset($arg_array['midCategoryID']) && is_numeric($arg_array['midCategoryID'])) {
            $sql .= ' AND midCategoryID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['midCategoryID'];
        }

        //使用标志
        if (isset($arg_array['useFlg']) && in_array($arg_array['useFlg'], array(0, 1))) {
            $sql .= ' AND useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }


        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计分类数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM goods_midcategory ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM goods_midcategory ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {

                $item_array[] = array(
                    'bigCategoryID' => $item->bigCategoryID,
                    'midCategoryID' => $item->midCategoryID,
                    'name' => $item->description,
                    'useFlg' => $item->useFlg,
                    'sortOrder' => $item->sortOrder,
                    'link' => $this->setCategoryLink( $item->bigCategoryID, $item->midCategoryID )
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }


    /**
     * 查询小分类信息
     * @param $arg_array
     * @return array|null
     */
    public function searchSmallCategory( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //大分类ID
        if (isset($arg_array['bigCategoryID']) && is_numeric($arg_array['bigCategoryID'])) {
            $sql .= ' AND bigCategoryID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['bigCategoryID'];
        }

        //中分类ID
        if (isset($arg_array['midCategoryID']) && is_numeric($arg_array['midCategoryID'])) {
            $sql .= ' AND midCategoryID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['midCategoryID'];
        }

        //中分类ID
        if (isset($arg_array['smallCategoryID']) && is_numeric($arg_array['smallCategoryID'])) {
            $sql .= ' AND smallCategoryID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['smallCategoryID'];
        }

        //使用标志
        if (isset($arg_array['useFlg']) && in_array($arg_array['useFlg'], array(0, 1))) {
            $sql .= ' AND useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }


        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计分类数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM goods_smallcategory ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM goods_smallcategory ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {

                $item_array[] = array(
                    'bigCategoryID' => $item->bigCategoryID,
                    'midCategoryID' => $item->midCategoryID,
                    'smallCategoryID' => $item->smallCategoryID,
                    'name' => $item->description,
                    'useFlg' => $item->useFlg,
                    'sortOrder' => $item->sortOrder,
                    'link' => $this->setCategoryLink( $item->bigCategoryID, $item->midCategoryID, $item->smallCategoryID )
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 生成商品条形码
     * @param int $postID 三级网购号
     * @return string
     */
    public function getBarcode($postID) {

		if(!is_numeric($postID)) {
            return $postID;
        }

		$year = date('Y');
		
		$barcode_length = strlen($year) + strlen($postID);
		$zero_length = 14 - $barcode_length;
		$zero_str = '';
		for($i = 0; $i < $zero_length; $i++){
			$zero_str .= '0';
		}
		
		return $year . $zero_str . $postID;

	}

    /**
     * 查询商品品牌信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *      'sortname' => string 排序字段
     *      'sortorder' => string 排序方式
     *      'page' => int 分页页码
     *      'rp' => int 分页页数
     * )
     * @return array|null
     */
    public function searchGoodsBrand( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //品牌号
        if (isset($arg_array['brandID']) && is_numeric($arg_array['brandID'])) {
            $sql .= ' AND brandID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['brandID'];
        }

        //品牌名称
        if (isset($arg_array['brandName']) && !empty($arg_array['brandName'])) {
            $sql .= ' AND brandName LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . trim($arg_array['brandName']) . '%';
        }

        //使用标志
        if (isset($arg_array['useFlg']) && is_numeric($arg_array['useFlg'])) {
            $sql .= ' AND useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp'])) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM goods_brand ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname'])) {
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);
                }


                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM goods_brand ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $timeStamp = strtotime($item->timeStamp);
                $item_array[] = array(
                    'brandID'       => $item->brandID,
                    'brandName'     => $item->brandName,
                    'description'   => $item->description,
                    'logo'          => $item->logo ? G_IMAGE_URL . $item->logo .'?timeStamp='.$timeStamp : '',
                    'sortOrder'     => $item->sortOrder,
                    'useFlg'        => $item->useFlg,
                    'useName'       => $item->useFlg ? '启用' : '禁用',
                    'tagID'         => $item->tagID
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 新增或修改商品品牌信息
     * @param array $arg_array 品牌参数
     * @return array
     */
    public function editBrandInfo( $arg_array ) {

        //实例化公共类
        $commHandler = new commHandler();

        //实例化文件类
        $fileDirHandler = new fileDirHandler();

        //参数检查
        if (!isset($arg_array['brandName'] ,$arg_array['sortOrder'] , $arg_array['brand_img'],$arg_array['description'],$arg_array['useFlg'],
            $arg_array['operator']) || empty($arg_array['operator'])) {
            return array( 'code' => 400, 'message' => '参数错误');
        }

        if (empty($arg_array['brandName'])) {
            return array( 'code' => 400, 'message' => '品牌名称不能为空');
        }

        if (!$commHandler->isInteger($arg_array['sortOrder'], 1)) {
            return array( 'code' => 400, 'message' => '排序序号必须为数字');
        }

        if (!in_array($arg_array['useFlg'], array(0, 1))) {
            $arg_array['useFlg'] = 1;
        }

        if (!isset($arg_array['brand_img']) || empty($arg_array['brand_img'])) {
            $arg_array['brand_img'] = null;
        }

        if (!isset($arg_array['brandID']) || empty($arg_array['brandID'])) {
            $arg_array['brandID'] = 0;
        }

        if (empty($arg_array['brand_img'])) {
            $oldName = null;
        } else {
            $oldName = G_APPLICATION_BASEPATH . $arg_array['brand_img'];
            $newName = G_IMAGE_SAVE_ROOT . 'brand/' . $fileDirHandler->basename($oldName);
        }

        $old_brand_log = null;

        try{

            $this->dbca->beginTransaction();

            //根据排序序号查询品牌信息
            $search_sql = 'SELECT brandID FROM goods_brand WHERE sortOrder = ?';
            $brand_array = &$this->dbca->stmt_query($search_sql, 'i', $arg_array['sortOrder']);

            //保存品牌信息
            $brand_obj = new entity('goods_brand');
            if ($arg_array['brandID'] > 0) {

                $brand_obj->brandID = $arg_array['brandID'];
                if (!$this->dbca->fetch($brand_obj)) {
                    throw new Exception('商品品牌信息没有找到', 404);
                }

                if ($brand_array && $brand_array[0]->brandID != $arg_array['brandID']) {
                    throw new Exception('排序序号已经被使用' , 404 ) ;
                }

                //更新商品列表里的品牌名称
                $this->dbca->stmt_query('UPDATE goods_list SET brandName=? WHERE brandID=?','si' , $arg_array['brandName'], $arg_array['brandID']) ;
                $this->dbca->stmt_query('UPDATE goods_list_edit SET brandName=? WHERE brandID=?','si' ,$arg_array['brandName'], $arg_array['brandID']) ;
                $this->dbca->stmt_query('UPDATE goods_sale SET brandName=? WHERE brandID=?','si' ,$arg_array['brandName'], $arg_array['brandID']) ;
                $this->dbca->stmt_query('UPDATE goods_sale_edit SET brandName=? WHERE brandID=?','si' ,$arg_array['brandName'], $arg_array['brandID']) ;

                $brand_obj->editor = $arg_array['operator'];

                //更新商品品牌标签
//                $tag_array  = array(
//                    'tagName'     => $arg_array['brandName'],
//                    'tagID'       => $brand_obj->tagID,
//                    'tagGroupID' => BRAND_TAGGROUPID,
//                    'creator'    => $arg_array['operator']
//                ) ;
//                $resultData = $this->commPropertyTag ( $tag_array ) ;
//                if($resultData['code'] == 400) {
//                    throw new Exception($resultData['message'], 400 ) ;
//                }


            } else {

                if ($brand_array) {
                    throw new Exception('排序序号已经被使用' , 404 ) ;
                }

                $brand_obj->creator = $arg_array['operator'];

                //生成标签组
//                $tag_array  = array(
//                    'tagName'=> $arg_array['brandName'],
//                    'tagID' => 0,
//                    'tagGroupID' => BRAND_TAGGROUPID,
//                    'creator' => $arg_array['operator']
//                ) ;
//                $result_array = $this->commPropertyTag ($tag_array) ;
//                if ($result_array['code'] == 200) {
//                    $brand_obj->tagID = $result_array['message'];
//                }

            }


            if (!empty($newName) && file_exists($newName) == false) {
                if (!$fileDirHandler->move($oldName, $newName)) {
                    throw new Exception('商品品牌图片上传失败', 404);
                }
                $brand_obj->logo = 'brand/' . $fileDirHandler->basename($oldName);
            }

            if(empty($arg_array['brand_img'])){
                $brand_obj->logo    = null;
            }

            $brand_obj->tagID = 0;
            $brand_obj->brandName   = $arg_array['brandName'];
            $brand_obj->description = $commHandler->convertVar($arg_array['description']);
            $brand_obj->sortOrder   = $arg_array['sortOrder'];
            $brand_obj->useFlg      = $arg_array['useFlg'];
            $this->dbca->save( $brand_obj );

            $this->dbca->commit();

            if(empty($newName)) {
                $old_log = G_IMAGE_SAVE_ROOT. $brand_obj->logo;
                $fileDirHandler->unlink($old_log);
            }

            if ($arg_array['brandID'] > 0) {
            	return array( 'code' => 200, 'message' => '商品品牌更新成功' );
            } else {
            	return array( 'code' => 200, 'message' => '商品品牌保存成功' );
            }

        } catch( Exception $e ) {

            $this->dbca->rollBack();

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }
        }

    }

    /**
     * 品牌的使用和禁用
     * @param array $arg_array 品牌参数
     * @return unknown
     */
    public function changeBrandUse ( $arg_array ) {

        //检查参数
        if (!isset($arg_array['brandID']) || !is_numeric($arg_array['brandID'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        try{

            $brand_obj = new entity('goods_brand');
            $brand_obj->brandID = $arg_array['brandID'];
            if (!$this->dbca->fetch($brand_obj)) {
                throw new Exception('商品品牌信息没有找到', 404);
            }
            if ($brand_obj->useFlg) {
                $brand_obj->useFlg = 0;
            } else {
                $brand_obj->useFlg = 1;
            }
            $this->dbca->save($brand_obj);

            if ($brand_obj->useFlg) {
                return array( 'code' => 200, 'message' => sprintf('商品品牌「%s」启用成功', $brand_obj->brandName) );
            } else {
                return array( 'code' => 200, 'message' => sprintf('商品品牌「%s」禁用成功', $brand_obj->brandName) );
            }

        } catch( Exception $e ) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }


    /**
     * 删除品牌
     *
     */
    public function deleteBrand ( $arg_array ) {

        if (!isset($arg_array['b_array'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        if (!isset($arg_array['b_array'][0])) {
            return array( 'code' => 400, 'message' => '请选择需要删除的商品品牌' );
        }

        $delete_array = $arg_array['b_array'];

        $tag_id_str = '';

        try {
        	
        	//检查品牌是否存在商品
        	foreach ($delete_array as $check_brandID) {
        		
        		//检查品牌是否有对应商品
                $goods_list      = $this->dbca->stmt_query('SELECT * FROM goods_list WHERE brandID = ?', 'i', $check_brandID);
                $goods_list_edit = $this->dbca->stmt_query('SELECT * FROM goods_list_edit WHERE brandID = ?', 'i', $check_brandID);
                $goods_sale      = $this->dbca->stmt_query('SELECT * FROM goods_sale WHERE brandID = ?', 'i', $check_brandID);
                $goods_sale_edit = $this->dbca->stmt_query('SELECT * FROM goods_sale_edit WHERE brandID = ?', 'i', $check_brandID);
                
                $goods_brand = new entity('goods_brand');
                $goods_brand->brandID = $check_brandID;
                if (!$this->dbca->fetch($goods_brand)) {
                	return array('code' => 400, 'message' => sprintf('品牌号「%d」信息未找到，请核实', $check_brandID));
                }
                
                if ($goods_list || $goods_list_edit || $goods_sale || $goods_sale_edit) {
                	return array('code' => 400, 'message' => sprintf('品牌「%s」存在商品信息，不能删除',$goods_brand->brandName));
                }
        	}

            //循环删除品牌
            foreach( $delete_array as &$brandID ) {

                //查询品牌信息
                $brand_obj = new entity('goods_brand');
                $brand_obj->brandID = $brandID;
                if ($this->dbca->fetch( $brand_obj )) {

                    $this->dbca->delete( $brand_obj );

                    if (empty($brand_obj->tagID)) {
                        continue;
                    }

                    if(empty($tag_id_str)) {
                        $tag_id_str .= $brand_obj->tagID;
                    } else {
                        $tag_id_str .= '_' . $brand_obj->tagID;
                    }

                }

            }

            //删除品牌标签
            $this->deleteTag(array('delete_str' => $tag_id_str)) ;

            return array( 'code' => 200, 'message' => '商品品牌删除成功' );

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }
    }

    /**
     * 规格组的使用和禁用
     *
     * @param unknown_type $arg_array
     * @return unknown
     */

    public function changeUse($arg_array){

        if (!isset($arg_array['specGroupID']) || $arg_array['specGroupID'] == '')
            return array( 'code' => 400, 'message' => '缺少参数' );

        //查询规格组是否存在或已经被操作
        $tagGroupInfo = new entity('goods_spec_group');
        $tagGroupInfo->specGroupID = $arg_array['specGroupID'] ;
        if (!$this->dbca->fetch( $tagGroupInfo ))
            return array( 'code' => 400, 'message' => sprintf('商品规格号「%d」信息未找到，请核实',$arg_array['specGroupID'] ));

        //检查规格组状态是否已经修改
        if($tagGroupInfo->useFlg == $arg_array['useFlg']  && $arg_array['useFlg'] == 1)
            return array( 'code' => 400, 'message' => sprintf('商品规格「%s」已启用',$tagGroupInfo->specGroupName ));

        if($tagGroupInfo->useFlg == $arg_array['useFlg'] && $arg_array['useFlg'] == 0)
            return array( 'code' => 400, 'message' => sprintf('商品规格「%s」已禁用',$tagGroupInfo->specGroupName ));

        //修改规格组状态
        $tagGroupInfo->useFlg = $arg_array['useFlg'] ;
        $this->dbca->save( $tagGroupInfo , 'goods_spec_group' );

        if($arg_array['useFlg'] == 1)
            return array( 'code' => 200, 'message' => sprintf('商品规格「%s」启用成功',$tagGroupInfo->specGroupName ) );

        else if ($arg_array['useFlg'] == 0)
            return array( 'code' => 200, 'message' => sprintf('商品规格「%s」禁用成功',$tagGroupInfo->specGroupName ) );
    }
    
    /**
     * 保存外部编号
     *
     * @param unknown_type $goods_code_array
     */
    public function save_goods_code($goods_code_array){
    	
    	if (empty($goods_code_array)) {
    		throw new Exception('请输入商家编码', -1000);
    	}

		$save_goods_code = new entity('goods_code');
		$save_goods_code->goodsCode = $goods_code_array['goodsCode'];
		if (!$this->dbca->fetch($save_goods_code)) {
			$save_goods_code->creator      = $goods_code_array['creator'];
    		$save_goods_code->postID       = $goods_code_array['postID'];
    		$save_goods_code->goodsID      = $goods_code_array['goodsID'];
    		$save_goods_code->product_code = $goods_code_array['product_code'];
    		$this->dbca->save($save_goods_code);
		} else {
			throw new Exception(sprintf('商家编码「%s」已经存在', $goods_code_array['goodsCode']), -1000);
		}
    	
    }
    
    /**
     * 修改分类排序
     *
     */
    public function changeSort($arg_array){
    	
    	//检查参数
    	if (!isset($arg_array['categoryID'], $arg_array['level'], $arg_array['sortOrder'])) {
    		return array('code' => 400, 'message' => '缺少参数', 'data' => array('categoryID' =>$arg_array['categoryID'], 'type' => 1));
    	}
    	
    	switch ($arg_array['level']) {
    		case 1:	//大分类
    			$sort_category = new entity('goods_bigcategory');
    			$sort_category->sortOrder = $arg_array['sortOrder'];
    			
    			$save_category = new entity('goods_bigcategory');
    			$save_category->bigCategoryID = $arg_array['categoryID'];
    		break;
    		case 2:	//中分类
    			$sort_category = new entity('goods_midcategory');
    			$sort_category->sortOrder = $arg_array['sortOrder'];
    			
    			$save_category = new entity('goods_midcategory');
    			$save_category->midCategoryID = $arg_array['categoryID'];
    		break;
    		case 3:	//小分类
    			$sort_category = new entity('goods_smallcategory');
    			$sort_category->sortOrder = $arg_array['sortOrder'];
    			
    			$save_category = new entity('goods_smallcategory');
    			$save_category->smallCategoryID = $arg_array['categoryID'];
    		break;
    		default:
    			return array('code' => 400, 'message' => '参数错误', 'data' => array('categoryID' =>$arg_array['categoryID'], 'type' => 1));	
    		break;	
    	}
    	
    	if (!$this->dbca->fetch($save_category)) {
    		return array('code' => 400, 'message' => sprintf('分类号「%s」信息未找到，请核实', $arg_array['categoryID']), 'data' => array('categoryID' =>$arg_array['categoryID'], 'type' => 1));	
    	}
    	
    	if ($this->dbca->fetch($sort_category)) {
    		switch ($arg_array['level']) {
    			case 1:
    				if ($sort_category->bigCategoryID != $arg_array['categoryID']) {
    					return array('code' => 400, 'message' => sprintf('排列序号「%s」已经存在', $arg_array['sortOrder']), 'data' => array('categoryID' =>$arg_array['categoryID'], 'type' => 1));	
    				}
    			break;	
    			case 2:
    				if ($sort_category->midCategoryID != $arg_array['categoryID']) {
    					return array('code' => 400, 'message' => sprintf('排列序号「%s」已经存在', $arg_array['sortOrder']), 'data' => array('categoryID' =>$arg_array['categoryID'], 'type' => 1));	
    				}
    			break;
    			case 3:
    				if ($sort_category->smallCategoryID != $arg_array['categoryID']) {
    					return array('code' => 400, 'message' => sprintf('排列序号「%s」已经存在', $arg_array['sortOrder']), 'data' => array('categoryID' =>$arg_array['categoryID'], 'type' => 1));	
    				}
    			break;
    		}
    	}
    	
    	$save_category->sortOrder = $arg_array['sortOrder'];
    	$this->dbca->save($save_category);

    	return array('code' => 200, 'message' => '排序修改成功');
    }
    
    /**
     * 修改分类名称
     *
     * @param unknown_type $arg_array
     * @return unknown
     */
     public function changeName($arg_array){
    	
    	//检查参数
    	if (!isset($arg_array['categoryID'], $arg_array['level'], $arg_array['categoryName'])) {
    		return array(
    			'code' 	  => 400, 
    			'message' => '缺少参数', 
    			'data'    => array('categoryID' => $arg_array['categoryID'], 'type' => 2)
    		);
    	}
    	
    	switch ($arg_array['level']) {
    		case 1:	//大分类
    			$sort_category = new entity('goods_bigcategory');
    			
    			$save_category = new entity('goods_bigcategory');
    			$save_category->bigCategoryID = $arg_array['categoryID'];
    			
    			//更新商品里面的分类名称
				$goods_list = sprintf('UPDATE goods_list SET TIMESTAMP=NOW(), bigCategoryName="%s" WHERE bigCategoryID=%d', $arg_array['categoryName'], $arg_array['categoryID']);
				$goods_list_edit = sprintf('UPDATE goods_list_edit SET TIMESTAMP=NOW(), bigCategoryName="%s" WHERE bigCategoryID=%d', $arg_array['categoryName'], $arg_array['categoryID']);
				$goods_sale = sprintf('UPDATE goods_sale SET TIMESTAMP=NOW(), bigCategoryName="%s" WHERE bigCategoryID=%d', $arg_array['categoryName'], $arg_array['categoryID']);
				$goods_sale_edit = sprintf('UPDATE goods_sale_edit SET TIMESTAMP=NOW(), bigCategoryName="%s" WHERE bigCategoryID=%d', $arg_array['categoryName'], $arg_array['categoryID']);
				
    		break;
    		case 2:	//中分类
    			$sort_category = new entity('goods_midcategory');
    			
    			$save_category = new entity('goods_midcategory');
    			$save_category->midCategoryID = $arg_array['categoryID'];
    			
    			//更新商品里面的分类名称
				$goods_list = sprintf('UPDATE goods_list SET TIMESTAMP=NOW(), midCategoryName="%s" WHERE midCategoryID=%d', $arg_array['categoryName'], $arg_array['categoryID']);
				$goods_list_edit = sprintf('UPDATE goods_list_edit SET TIMESTAMP=NOW(), midCategoryName="%s" WHERE midCategoryID=%d', $arg_array['categoryName'], $arg_array['categoryID']);
				$goods_sale = sprintf('UPDATE goods_sale SET TIMESTAMP=NOW(), midCategoryName="%s" WHERE midCategoryID=%d', $arg_array['categoryName'], $arg_array['categoryID']);
				$goods_sale_edit = sprintf('UPDATE goods_sale_edit SET TIMESTAMP=NOW(), midCategoryName="%s" WHERE midCategoryID=%d', $arg_array['categoryName'], $arg_array['categoryID']);
    			
    		break;
    		case 3:	//小分类
    			$sort_category = new entity('goods_smallcategory');
    			
    			$save_category = new entity('goods_smallcategory');
    			$save_category->smallCategoryID = $arg_array['categoryID'];
    			
    			//更新商品里面的分类名称
				$goods_list = sprintf('UPDATE goods_list SET TIMESTAMP=NOW(), smallCategoryName="%s" WHERE smallCategoryID=%d', $arg_array['categoryName'], $arg_array['categoryID']);
				$goods_list_edit = sprintf('UPDATE goods_list_edit SET TIMESTAMP=NOW(), smallCategoryName="%s" WHERE smallCategoryID=%d', $arg_array['categoryName'], $arg_array['categoryID']);
				$goods_sale = sprintf('UPDATE goods_sale SET TIMESTAMP=NOW(), smallCategoryName="%s" WHERE smallCategoryID=%d', $arg_array['categoryName'], $arg_array['categoryID']);
				$goods_sale_edit = sprintf('UPDATE goods_sale_edit SET TIMESTAMP=NOW(), smallCategoryName="%s" WHERE smallCategoryID=%d', $arg_array['categoryName'], $arg_array['categoryID']);
    			
    		break;
    		default:
    			return array(
    				'code'   => 400, 
    				'message' => '参数错误', 
    				'data'    => array('categoryID' => $arg_array['categoryID'], 'type' => 2)
    			);	
    		break;	
    	}

    	if (!$this->dbca->fetch($save_category)) {
    		return array(
    			'code'    => 400, 
    			'message' => sprintf('分类号「%s」信息未找到，请核实', $arg_array['categoryID']), 
    			'data'    => array('categoryID' => $arg_array['categoryID'], 'type' => 2)
    		);	
    	}
    	
    	//分类是否重复
    	$sort_category->description = $arg_array['categoryName'];
    	if ($this->dbca->fetch($sort_category)) {
//    		switch ($arg_array['level']) {
//    			case 1:
//    				if ($sort_category->bigCategoryID != $arg_array['categoryID']) {
//    					return array(
//    						'code'    => 400, 
//    						'message' => sprintf('分类名称「%s」已经存在', $arg_array['categoryName']), 
//    						'data'    => array('categoryID' => $arg_array['categoryID'], 'type' => 2)
//    					);	
//    				}
//    			break;	
//    			case 2:
//    				if ($sort_category->midCategoryID != $arg_array['categoryID']) {
//    					return array(
//    						'code'    => 400, 
//    						'message' => sprintf('分类名称「%s」已经存在', $arg_array['categoryName']), 
//    						'data'    => array('categoryID' => $arg_array['categoryID'], 'type' => 2)
//    					);
//    				}
//    			break;
//    			case 3:
//    				if ($sort_category->smallCategoryID != $arg_array['categoryID']) {
//    					return array(
//    						'code'    => 400, 
//    						'message' => sprintf('分类名称「%s」已经存在', $arg_array['categoryName']), 
//    						'data'    => array('categoryID' => $arg_array['categoryID'], 'type' => 2)
//    					);
//    				}
//    			break;
//    		}
    	}
    	
    	$save_category->description = $arg_array['categoryName'];
    	
    	$this->dbca->beginTransaction();
    	try {
    		$this->dbca->save($save_category);
    		
    		$this->dbca->stmt_query($goods_list);
    		$this->dbca->stmt_query($goods_list_edit);
    		$this->dbca->stmt_query($goods_sale);
    		$this->dbca->stmt_query($goods_sale_edit);
    		
    		$this->dbca->commit();
    		
    		return array('code' => 200, 'message' => '排序修改成功');
    		
    	}catch (Exception $e) {
    		$this->dbca->rollBack();
    		return array(
				'code'    => 400, 
				'message' => '分类名称修改失败', 
				'data'    => array('categoryID' => $arg_array['categoryID'], 'type' => 2)
			);
    	}

    }

    /**
     * 保存商品扩展属性
     *
     * @param unknown_type $postID
     * @param unknown_type $data
     * @param unknown_type $currentUserID
     * @return unknown
     */
    public function saveGoodsExtend($postID , $data , $currentUserID){
    	
		if( !isset( $postID ) || empty( $postID ) )
            return array('message'=>'参数错误' , 'code'=>400);

        if( empty($data) )
            return array('message'=>'请输入至少一个商品扩展属性' , 'code'=>400);

        if( empty($currentUserID) )
            return array('message'=>'当前操作人不能为空' , 'code'=>400);

        //检查商品是否存在
        $check_obj = new entity('goods_list_edit');
        $check_obj->postID = $postID;

        if( !$this->dbca->fetch($check_obj) ){
            return  array('message'=>sprintf('网购号「%d」商品不存在' , $postID) , 'code'=>404);
        }

        $goodsID = $check_obj->goodsID;
        $product_code = $check_obj->product_code;

        try{

            //删除该商品原来的关键字
            $delete_sql = 'DELETE FROM goods_extend WHERE postID = ?';

            //删除原来的关键字
            $this->dbca->stmt_query($delete_sql,'i',$postID);
			$sortOrder = 1;
            foreach( $data as $val ){

                $extend_obj = new entity('goods_extend');
                $extend_obj->postID       = $postID;
                $extend_obj->name         = $val[0];
                $extend_obj->goodsID      = $goodsID;
                $extend_obj->product_code = $product_code;
                $extend_obj->value        = $val[1];
                $extend_obj->creator      = $currentUserID;
                $extend_obj->sortOrder    = $sortOrder;

                $this->dbca->save( $extend_obj );
				$sortOrder++;
            }

            return array('message'=>'保存成功' , 'code'=>200);

        }catch ( Exception $e ){

            //开启事务
            $this->dbca->rollBack();
            error_log( $e->getMessage() );
            return array('message'=>'系统错误，保存失败' , 'code'=>500);
        }
    }
    /**
     * 查询商品扩展属性
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
            'postID' => int 二级网购号
            'sortname' => string 排序字段
            'sortorder' => string 排序方式
            'page' => int 分页页码
            'rp' => int 分页页数
     * )
     * @return null|array
     */
    public function searchGoodsExtend( &$arg_array ) {
    	
        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //二级网购号
        if (isset($arg_array['postID']) && is_numeric($arg_array['postID'])) {
            $sql .= ' AND postID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['postID'];
        }

        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计分类数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM goods_extend ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM goods_extend ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            $goodsHandler = new goodsHandler();

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'postID' => $item->postID,
                    'goodsID' => $item->goodsID,
                    'product_code' => $item->product_code,
                    'name' => $item->name,
                    'value' => $item->value
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }
    
    /**
     * 查询商品销售排行
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *      'sortname' => string 排序字段
     *      'sortorder' => string 排序方式
     *      'page' => int 分页页码
     *      'rp' => int 分页页数
     * )
     * @return array|null
     */
    public function searchGoodsSaleStat( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //品牌号
        if (isset($arg_array['saletotal']) && is_numeric($arg_array['saletotal'])) {
            $sql .= ' AND saletotal = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['saletotal'];
        }
		
        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp'])) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM goods_sale_stat ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname'])) {
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);
                }


                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM goods_sale_stat ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $timeStamp = strtotime($item->timeStamp);
                $item_array[] = array(
                    'postID'       => $item->postID,
                    'goodsID'     => $item->goodsID,
                    'goodsName'   => $item->goodsName,
                    'salePrice'   => $item->salePrice,
                    'addPoints'     => $item->addPoints,
                    'goodsMainPic'    => $item->goodsMainPic,
                    'uid'    => $item->uid,
                    'bigCategoryID'    => $item->bigCategoryID,
                    'middleCategoryID'    => $item->middleCategoryID,
                    'smallCategoryID'   => $item->smallCategoryID,
                    'saletotal'       => $item->saletotal,
                    'saledaytotal'    => $item->saledaytotal
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }
    
    /**
     * 保存二级商品和分类映射关系
     *
     * @param unknown_type $goods_category_array
     * @param unknown_type $goodsCategory
     */
    public function save_category_goods($goods_category_array, $goodsCategory){
    	if (empty($goods_category_array) || empty($goodsCategory)) {
    		throw new Exception('商品录入失败', -1000);
    	}
    	
    	foreach ($goods_category_array as $goods) {
    		foreach ($goodsCategory as $category) {
    			$save_goods_category_relation = new entity('goods_category_relation');
    			$save_goods_category_relation->bigCategoryID   = $category[0];
    			$save_goods_category_relation->midCategoryID   = $category[1];
    			$save_goods_category_relation->smallCategoryID = $category[2];
    			$save_goods_category_relation->postID = $goods->postID;
    			if (!$this->dbca->fetch($save_goods_category_relation)) {
	    			$save_goods_category_relation->creator = $goods->creator;
	    			$this->dbca->save($save_goods_category_relation);
    			}
    		}
    	}
    }
    
    /**
     * 组装列表页标签
     *
     */
    public function listTagInfo( $arg_array ){
    	
    	//返回的标签数组
    	$tag_group_array = array();
    	
    	//已选择标签数组
    	$select_group_array = array();
    	
    	//处理已选择的标签
    	$extend_array = array();
    	if (isset($arg_array['extend']) && $arg_array['extend']) {
    		$temp_extend_array = explode(',',$arg_array['extend']);
	    	if ($temp_extend_array) {
	    		foreach ($temp_extend_array as $e) {
	    			$temp = explode('_',$e);
	    			$extend_array[$temp[0]] = $temp[1];
	    		}
	    	}
    	}
    	
    	//获取扩展数组的键值【即标签组ID】
    	$extend_keys_array = array_keys($extend_array);
		
    	//查找标签组
		$sql = 'SELECT gtg.tagGroupID,gtg.tagGroupName FROM goods_category_tagGroup gct 
					JOIN goods_tag_group gtg ON gct.tagGroupID = gtg.tagGroupID';
		$tag_group_result = $this->dbca->stmt_query($sql);
		
		if ($tag_group_result) {
			foreach ($tag_group_result as $value) {
				
				$tag_group_array[$value->tagGroupID] = array(
					'tagGroupID' => $value->tagGroupID,
					'tagGroupName' => $value->tagGroupName,
					'tags' => array()
				);
				
				if (in_array($value->tagGroupID,$extend_keys_array)) {
					$select_group_array[$value->tagGroupID] = array(
						'tagGroupID' => $value->tagGroupID,
						'tagGroupName' => $value->tagGroupName,
						'tags' => array()
					);
				}
				
			}
		}
		
		foreach ($tag_group_array as $tag_group) {
			
			$temp_extend_str = '';
			$temp_extend = '';
			foreach ($extend_array as $k=>$v) {
				if ($tag_group['tagGroupID'] == $k) {
					continue;
				}
				$temp_extend_str .= $k.'_'.$v.',';
			}
			
			
			
			$sql = 'SELECT tagID,tagName,tagGroupID FROM goods_tag WHERE tagGroupID = ' . $tag_group['tagGroupID'];
			$tag_array = $this->dbca->stmt_query($sql);
			
			foreach ($tag_array as $tag) {
				
				//判断当前标签组是否已选择
				if (in_array($tag->tagGroupID,$extend_keys_array)) {
					foreach ($extend_array as $k=>$v) {
						if ($tag->tagGroupID == $k && $tag->tagID == $v) {
							if ($temp_extend_str) {
								$temp_str = substr($temp_extend_str,0,-1);
							} else {
								$temp_str = '';
							}
							$temp_extend = $temp_str ? $temp_str : 0;
							$link = '/shop/list-'.$arg_array['uid'].'-'.$arg_array['sortby'].'-'.$arg_array['sort'].'-'.$arg_array['pageindex'].'-'.$temp_extend.'.html';
					
							$select_group_array[$tag->tagGroupID]['tags'][$tag->tagID] = array(
								'tagID' => $tag->tagID,
								'tagGroupID' => $tag->tagGroupID,
								'tagName' => $tag->tagName,
								'link' => $link,
								'flg' => 1
							);
						}
					}
				} else {
					
					$flg = 0; //已选择标记
					foreach ($extend_array as $k=>$v) {
						if ($tag->tagGroupID == $k && $tag->tagID == $v) {
							$flg = 1;
						}
					}
					
					if ($flg == 1) {
						if ($temp_extend_str) {
							$temp_str = substr($temp_extend_str,0,-1);
						} else {
							$temp_str = '';
						}
						$temp_extend = $temp_str ? $temp_str : 0;
					} else {
						$temp_extend = $temp_extend_str . $tag->tagGroupID.'_'.$tag->tagID;
					}
					
					$link = '/shop/list-'.$arg_array['uid'].'-'.$arg_array['sortby'].'-'.$arg_array['sort'].'-'.$arg_array['pageindex'].'-'.$temp_extend.'.html';
					
					$tag_group_array[$tag->tagGroupID]['tags'][$tag->tagID] = array(
						'tagID' => $tag->tagID,
						'tagGroupID' => $tag->tagGroupID,
						'tagName' => $tag->tagName,
						'link' => $link,
						'flg' => $flg
					);
				}
			}
			
		}
		
		return array('tag_group_array' => $tag_group_array, 'select_group_array' => $select_group_array);
    }
    
    /** 
     * 组装并发sql数组(每行条件合并查询)
     * $perPage 每页显示多少条数据,默认30
     * @param array $arg_array 参数数组
     * @return mix
     */
	public function concurrent_merge_row_sql ( $arg_array ) {
		
		$sqlStr = '';
		//大分类
		if (isset($arg_array['big_category_id']) && !empty($arg_array['big_category_id'])) {
			$sqlStr .= ' gcr.bigCategoryID = ' . $arg_array['big_category_id'];
		}
		
		//中分类
		if (isset($arg_array['middle_category_id']) && !empty($arg_array['middle_category_id'])) {
			$sqlStr .= ' AND gcr.midCategoryID = ' . $arg_array['middle_category_id'];
		}
		
		//小分类
		if (isset($arg_array['small_category_id']) && !empty($arg_array['small_category_id'])) {
			$sqlStr .= ' AND gcr.smallCategoryID = ' . $arg_array['small_category_id'];
		}
		
		//库存上下架
		$sqlStr .= ' AND gl.useFlg = 1 AND gl.forSale = 1 AND addPoints <= 0 ';
		
		//判断扩展属性
		$extend_array = array();
		if (isset($arg_array['extend']) && $arg_array['extend']) {
			$temp_ext_array = explode(',',$arg_array['extend']);
			foreach ($temp_ext_array as $tag_str) {
				$inner_temp = explode('_',$tag_str);
				$extend_array[$inner_temp[0]] = $inner_temp[1];
			}
		}
		
		$i = 0;
		$brand_tag = '';
		if (!is_array($extend_array) || empty($extend_array)) {
			return -100;
		}
		$parallelSet = new parallelSet();
		foreach ($extend_array as $key=>$value) {
			
			$each_tag = array();
			$each_tag['Arg'][] = $key;
			$each_tag['Arg'][] = $value;
			$sql = '(?)';
			$sql = 'SELECT gl.* FROM goods_list gl 
								INNER JOIN goods_category_relation gcr ON gl.postID = gcr.postID
								INNER JOIN ( 
								SELECT goodsID,threePostID FROM goods_tag_relation WHERE tagGroupID=? AND tagID IN '.$sql.' AND useFlg=1
					  ) AS T_s ON T_s.goodsID = gl.goodsID WHERE ' . $sqlStr;
			
			$parallelentity = new ParallelEntity();
			$parallelentity->setSql($sql);
			$parallelentity->setArg($each_tag['Arg']);
			$ID = $i++;
			$parallelentity->setParalleID(strval($ID));
			$parallelentity->setKeyField('postID');
			$parallelSet->pushEntitySet($parallelentity);
			unset($parallelentity);
			$brand_tag .= '( '.$ID.' )';
		}
		$method = str_replace(')(',') * (',$brand_tag);
		$start = (($arg_array['pageindex']-1) * $arg_array['perpage'])+1;
		$end = (($arg_array['pageindex']-1) * $arg_array['perpage']) + $arg_array['perpage'];
		switch ($arg_array['sortby']) {
			case 'update': 
				$sorter = 'postID';
				$type = 'int';
				break;
			case 'price':
				$sorter = 'salePrice';
				$type = 'float';
				break;
			case 'discount':
				$sorter = 'discount';
				$type = 'float';
				break;
			default:
				$sorter = 'saletotal';
				$type = 'int';
		}
		$expression = array(
		        'Orderby' => $sorter,
		        'Sort' => $arg_array['sort'],
		        'Type' => $type,
		        'From' => $start,
		        'To' => $end,
		        'Method' => $method
		    );
		$parallelSet->setParallelSetExpression($expression);
		return $parallelSet; 
	}
	
	/**
     * 查询购物须知
     * @param array $arg_array    
     * @return null|array
     */
    public function searchShoppingTips( &$arg_array ) {
        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //分类号
        if (isset($arg_array['itemCategoryID']) && is_numeric($arg_array['itemCategoryID'])) {
            $sql .= ' AND itemCategoryID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['itemCategoryID'];
        }
		
        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计分类数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM sys_item ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM sys_item ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;


            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'itemID' => $item->itemID,
                    'itemName' => $item->itemName,
                    'itemCategoryID' => $item->itemCategoryID,
                    'useFlg' => $item->useFlg,
                    'remark' => $item->extend_1,
                    'description' => $item->extend_2,
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }
	
}